How to change quicksort to output elements in descending order?

Posted by masato-san on Stack Overflow See other posts from Stack Overflow or by masato-san
Published on 2010-06-01T18:51:21Z Indexed on 2010/06/01 18:53 UTC
Read the original article Hit count: 273

Filed under:
|

Hi,

I wrote a quicksort algorithm however, I would like to make a change somewhere so that this quicksort would output elements in descending order.

I searched and found that I can change the comparison operator (<) in partition() to other way around (like below).

 //This is snippet from partition() function    
        while($array[$l] < $pivot) { $l++; }
        while($array[$r] > $pivot) { $r--; }

But it is not working..

If I quicksort the array below, $array = (3,9,5,7);

should be:

$array = (9,7,5,3)

But actual output is:

$array = (3,5,7,9)

Below is my quicksort which trying to output elements in descending order. How should I make change to sort in descending order? If you need any clarification please let me know. Thanks!

$array = (3,9,5,7);
$app = new QuicksortDescending();
$app->quicksort($array, 0, count($array));
print_r($array);


class QuicksortDescending {

public function partitionDesc(&$array, $left, $right) {
        $l = $left;
        $r = $right;
        $pivot = $array[($right+$left)/2];

        while($l <= $r) {
            while($array[$l] > $pivot) { $l++; }
            while($array[$r] < $pivot) { $r--; }
            if($l <= $r) {// if L and R haven't cross
                $this->swap($array, $l, $r);
                $l ++;
                $j --;
            }
        }
        return $l;
    }


public function quicksortDesc(&$array, $left, $right) {
        $index = $this->partition($array, $left, $right);
        if($left < $index-1) { //if there is more than 1 element to sort on right subarray
            $this->quicksortDesc($array, $left, $index-1);
        }
        if($index < $right) { //if there is more than 1 element to sort on right subarray
            $this->quicksortDesc($array, $index, $right);
        }
    }

}

© Stack Overflow or respective owner

Related posts about php

Related posts about quicksort