Ben bu quicksort çıkış elemanları azalan olacağını, böylece bir yerde bir değişiklik yapmak istiyorum, ancak bir quicksort algoritması yazdı.
Ben arandı ve (aşağıda) gibi çevresindeki diğer şekilde bölüme karşılaştırma operatörü (<) () değiştirebilirsiniz bulundu.
//This is snippet from partition() function
while($array[$l] < $pivot) { $l++; }
while($array[$r] > $pivot) { $r--; }
Ama çalışmıyor ..
If I quicksort the array below, $array = (3,9,5,7);
olmalıdır:
$ Dizi = (9,7,5,3)
Ama gerçek çıktı:
$ Dizi = (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;
}
}