开发者

How to change quicksort to output elements in descending order?

I wrote a开发者_Python百科 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 = array(3,9,5,7);
$app = new QuicksortDescending();
$app->quicksortDesc($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->partitionDesc($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);
        }
    }

public function swap(&$array, $index1, $index2) {
        $tmp = $array[$index1];
        $array[$index1] = $array[$index2];
        $array[$index2] = $tmp;

    }

}


Just swap the comparison operators < with > and vice versa when comparing two elements:

while($array[$l] < $pivot) { $l++; }
while($array[$r] > $pivot) { $r--; }


Instead of changing the quicksort implementation, iterate the array from the end:

for ($i = count($array)-1; $i>=0; $i--) {
  // do something with $array[$i];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜