Okay, so I'm doing some serious jiggerpokery with OOP in PHP, and I've got to roll my own sort algorithm. (I'm sorting an array of objects by a property of one of the child objects.) So I went out and picked up some quicksort pseudocode:
QuickSort(A, p, r)
if p < r
then q = Partition(A,p,r)
Quicksort(A,p,q)
Quicksort(A,q+1,r) Notes:
initially call with
A = unsorted array
p = 1
r = size of (A)
Partition Pseudocode
Partition(A, p, r)
x = A[p]
i = p - 1
j = r + 1
while TRUE
do repeat j = j -1
until A[j] <= x
repeat i = i + 1
until A >= x
if i < j
then exchange A with A[j]
else return j
from http://astro.gmu.edu/classes/c80196/lecture3.html. This looks nothing like PHP, so here's what I did with it (roughly -- I don't want to bore and confuse you with the details of the OOP):
function quicksort($array, $p, $r) {
if ($p < $r) $q = partition($array, $p, $r)
quicksort($array, $p, $q)
quicksort($array, $q + 1, $r)
}
function partition($array, $p, $r) {
$x = $array[$p];
for ($j = $r + 1; $array[$j] <= $x; $j--) {
for ($i = $p - 1; $array[$i] >= $x; $i--) {
if ($i < $j) {
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
} else return $j
}
}
}
Now, there might be little typos in there because, as I noted, that's not exactly what I have due to my nasty OOP.
I've never done my own quicksort before, and the pseudocode was a little unclear to me, so I'm not sure my algorithm is right. Actually, I'm pretty sure it isn't right. The only PHP-code quicksort I can find is totally undecipherable (a lesson in meaningful variable names: http://pulsar.jb.com/sklar-php/code5.html), so can anyone tell me if I'm on the right track here? Maybe some suggestions as to what's wrong? Thanks.