Sorting
Quick Sort (Lomuto)
Choose the last item as a pivot, partition smaller values to its left, then recurse on the two sides.
Algorithm
Basic Implementation
basic.php
<?php
function partition(&$arr, $low, $high) {
$pivot = $arr[$high];
$i = $low - 1;
for ($j = $low; $j < $high; $j++) {
if ($arr[$j] <= $pivot) {
$i++;
$tmp = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $tmp;
}
}
$tmp = $arr[$i + 1]; $arr[$i + 1] = $arr[$high]; $arr[$high] = $tmp;
return $i + 1;
}
function quick_sort(&$arr, $low, $high) {
if ($low < $high) {
$pivot_index = partition($arr, $low, $high);
quick_sort($arr, $low, $pivot_index - 1);
quick_sort($arr, $pivot_index + 1, $high);
}
}
$arr = [4, 1, 5, 2, 3];
quick_sort($arr, 0, count($arr) - 1);
echo "[" . implode(", ", $arr) . "]
";
Complexity
- Time: O(n^2) worst, O(n log n) average
- Space: O(log n) average call stack
- Stable: no
Implementation notes
$arris the pinned PHP array literal[4, 1, 5, 2, 3].quick_sort(&$arr, $low, $high)andpartition(&$arr, $low, $high)take$arrby reference, so swaps mutate the same array that is later printed.- The pivot is the last slot in the active range:
$pivot = $arr[$high]. - Lomuto's left boundary starts as
$i = $low - 1, then$jscans from$lowup to$high - 1. - The comparison is
$arr[$j] <= $pivot; values1and2move left of pivot3, while4and5stay on the right in the first partition trace. - Swaps use a temporary variable:
$tmp = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $tmp;, then the pivot swaps into$i + 1. - The replay shows
[4, 1, 5, 2, 3]becoming[1, 4, 5, 2, 3], then[1, 2, 5, 4, 3], then[1, 2, 3, 4, 5]when pivot3lands at index2. - Recursive calls then cover
$low..$pivot_index - 1and$pivot_index + 1..$high; the trace records left[1, 2]and right[4, 5]already sorted. - The final
echoconcatenates[+implode(", ", $arr)+], then closes the quoted string after a literal newline, so it prints[1, 2, 3, 4, 5].
pivot
The final element is moved to the boundary between smaller and larger values.
partition
One scan rearranges the current range before the recursive calls.