I have this simple quicksort function (I got it from uncle “G”)
function quicksort( &$list, $l , $r ) {
$i = $l;
$j = $r;
$tmp = $list[(int)( ($l+$r)/2 )];
do {
while( $list[$i] < $tmp )
$i++;
while( $tmp < $list[$j] )
$j--;
if( $i <= $j ) {
$w = $list[$i];
$list[$i] = $list[$j];
$list[$j] = $w;
//_swp($list[$i],$list[$j]);
$i++;
$j--;
}
}while( $i <= $j );
if( $l < $j )
quicksort($list, $l, $j);
if( $i < $r )
quicksort($list, $i, $r);
return $list;
}
And I have this little function to swap two variables.
function _swp(&$a,&$b){
$a=$a+$b;
$b=$a-$b;
$a=$a-$b;
}
How come I can’t use _swp($a,$b) in quicksort function instead of this lines?
$w = $list[$i];
$list[$i] = $list[$j];
$list[$j] = $w;
If I comment out these 3 lines of code and enter call to _swp function I got bad results…
Please explain.
Best regards
the unexpected behavior is probably the “random” occurence of zeros in the sorted list. This happens because there is a special case while swapping:
The problem is found directly in the condition for swapping itself:
if $i==$jthen there are two references to the same variable. Thus calling_swp($list[$i],$list[$j]);will firstly add both variables$a = $a + $b. Considering $a and $b actually access the same variable content, $a and $b will then have the same value. In the next step$b = $a - $bwill then be zero as $a is equal to $b. The third operation will leave the result to 0.An easy solution for this is inserting another condition:
I hope this will help you.
Cheers,
Fabian