Home >Backend Development >PHP Tutorial >Quick sort recursive version php implementation
The content of this article is about the quick sorting recursive version of PHP implementation. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it.
Start reviewing the algorithm today, even the most familiar I can’t even write out the quick queue, I’m so embarrassed, I’ll post the code for future reference
function qSort(array &$a, $low, $high) { if($low >= $high) { return; } $index = partition($a,$low,$high); qSort($a,$low,$index-1); qSort($a,$index+1,$high); }
//元素相互赋值比交换效率 function partition(array &$a, $low, $high) { $temp = $a[$low]; while($low < $high) { while($low < $high && $a[$high] >= $temp) { --$high; } $a[$low] = $a[$high]; while($low < $high && $a[$low] <= $temp) { ++$low; } $a[$high] = $a[$low]; } $a[$low] = $temp; return $low; }
$a = [0,20,7,-1,6,2,6,2,8, 9,0,1];
qSort($a, 0, count($a) -1);
var_dump(implode(',', $a));
Result display: -1,0,0,1,2,2,6,6,7,8,9,20
Related recommendations:
Code Detailed explanation of how JavaScript implements quick sort
The above is the detailed content of Quick sort recursive version php implementation. For more information, please follow other related articles on the PHP Chinese website!