PHP Quick Sort Algorithm
last modified November 25, 2026
Quick sort is a divide-and-conquer sorting algorithm that partitions an array around a pivot and sorts the two parts recursively. It sorts in place, needs no second array for merging, and runs in O(n log n) on average, but its worst case is O(n2) and it is not stable.
This article implements quick sort in PHP, from a simple recursive version to an in-place Lomuto partition, and shows with comparison counts why the pivot choice and duplicate keys matter.
How quick sort works
Quick sort is a divide-and-conquer algorithm. It picks one element, called the pivot, rearranges the array so that smaller elements come before the pivot and larger ones after it, and then sorts the two parts recursively. A part with zero or one element is already sorted, which stops the recursion.
The rearrangement is called partitioning, and it is the part that determines both the speed and the memory use. The Lomuto scheme, used below, keeps the pivot at the end of the range and walks the range with a second index. Every element smaller than the pivot is swapped into a growing region at the front; at the end one swap puts the pivot between the two regions.
With balanced partitions the array is halved at every level, which gives log2 n levels of O(n) work and an average time of O(n log n). With unbalanced partitions the recursion has n levels and the time becomes O(n2). The algorithm sorts in place and needs only O(log n) stack space, but it is not stable: equal elements may change their relative order.
PHP's own sort, usort, and array_multisort are implemented in C and have been stable since PHP 8.0. They are faster than any implementation written in PHP, so quick sort is mainly interesting as an algorithm and as a way to understand partitioning.
A simple implementation
The first version keeps the code close to the description: take the first element as the pivot, split the rest into two arrays, sort both, and join the pieces.
<?php
declare(strict_types=1);
function quickSort(array $items): array
{
if (count($items) < 2) {
return $items;
}
$pivot = array_shift($items);
$left = [];
$right = [];
foreach ($items as $item) {
if ($item < $pivot) {
$left[] = $item;
} else {
$right[] = $item;
}
}
return [...quickSort($left), $pivot, ...quickSort($right)];
}
$numbers = [7, 2, 9, 4, 3, 8, 5];
echo implode(", ", quickSort($numbers)), "\n";
array_shift removes the pivot from the front of the array, and the loop compares every remaining element with it. Elements equal to the pivot go to the right, which is enough for correctness. The spread operator assembles the sorted left part, the pivot, and the sorted right part; the pivot is never compared again, because it is already in its final position.
$ php qs_simple.php 2, 3, 4, 5, 7, 8, 9
Partitioning in place
The simple version creates new arrays at every call. The in-place version reuses one array and partitions a range delimited by two indexes, which removes most of the copying.
<?php
declare(strict_types=1);
function partition(array &$items, int $low, int $high): int
{
$pivot = $items[$high];
$i = $low;
for ($j = $low; $j < $high; $j++) {
if ($items[$j] < $pivot) {
[$items[$i], $items[$j]] = [$items[$j], $items[$i]];
$i++;
}
}
[$items[$i], $items[$high]] = [$items[$high], $items[$i]];
return $i;
}
function quickSort(array &$items, int $low, int $high): void
{
if ($low >= $high) {
return;
}
$middle = partition($items, $low, $high);
quickSort($items, $low, $middle - 1);
quickSort($items, $middle + 1, $high);
}
$numbers = [7, 2, 9, 4, 3, 8, 5];
quickSort($numbers, 0, count($numbers) - 1);
echo implode(", ", $numbers), "\n";
In partition, $i marks the end of the region that holds values smaller than the pivot. The loop moves every smaller value into that region with a swap, and the final swap places the pivot at index $i. The function returns that index, and the recursion sorts the ranges on both sides of it. The two-element list assignment [$a, $b] = [$b, $a] swaps the values without a temporary variable.
$ php qs_lomuto.php 2, 3, 4, 5, 7, 8, 9
Why the pivot matters
The last element is a poor pivot for input that is already sorted. Every partition then produces one empty side and one side with all remaining elements, so the recursion has n levels instead of log2 n. The next example counts comparisons instead of measuring time, which gives the same numbers on every machine.
<?php
declare(strict_types=1);
function partitionCount(array &$items, int $low, int $high, int &$count, bool $middle): int
{
if ($middle) {
$mid = intdiv($low + $high, 2);
[$items[$mid], $items[$high]] = [$items[$high], $items[$mid]];
}
$pivot = $items[$high];
$i = $low;
for ($j = $low; $j < $high; $j++) {
$count++;
if ($items[$j] < $pivot) {
[$items[$i], $items[$j]] = [$items[$j], $items[$i]];
$i++;
}
}
[$items[$i], $items[$high]] = [$items[$high], $items[$i]];
return $i;
}
function quickSortCount(array &$items, int $low, int $high, int &$count, bool $middle): void
{
if ($low >= $high) {
return;
}
$p = partitionCount($items, $low, $high, $count, $middle);
quickSortCount($items, $low, $p - 1, $count, $middle);
quickSortCount($items, $p + 1, $high, $count, $middle);
}
foreach ([8, 16, 32, 64] as $n) {
$last = range(1, $n);
$lastCount = 0;
quickSortCount($last, 0, $n - 1, $lastCount, false);
$mid = range(1, $n);
$midCount = 0;
quickSortCount($mid, 0, $n - 1, $midCount, true);
echo "$n elements: last pivot $lastCount, middle pivot $midCount\n";
}
With the last element as pivot, 8 sorted elements need 28 comparisons, which is 8 · 7 / 2; 64 elements need 2016, which is 64 · 63 / 2. Doubling the input quadruples the work, the signature of O(n2). Moving the middle element to the end before partitioning splits the sorted input evenly, and the count grows a little faster than the input: 13, 38, 103, and 264. A random pivot gives a similar result on average, and PHP's mt_rand is enough for a real implementation.
$ php qs_counts.php 8 elements: last pivot 28, middle pivot 13 16 elements: last pivot 120, middle pivot 38 32 elements: last pivot 496, middle pivot 103 64 elements: last pivot 2016, middle pivot 264
Duplicate keys and three-way partitioning
Values that repeat cause the same problem from another direction. A two-way partition sends every element equal to the pivot to one side, so an array of identical values is a worst case even with a good pivot. A three-way partition groups smaller, equal, and larger elements in one pass and recurses only on the outer groups.
<?php
declare(strict_types=1);
$comparisons = 0;
function threeWay(array &$items, int $low, int $high, int &$count): array
{
$pivot = $items[$low];
$less = $low;
$i = $low;
$greater = $high;
while ($i <= $greater) {
$count++;
if ($items[$i] < $pivot) {
[$items[$less], $items[$i]] = [$items[$i], $items[$less]];
$less++;
$i++;
} elseif ($items[$i] > $pivot) {
[$items[$i], $items[$greater]] = [$items[$greater], $items[$i]];
$greater--;
} else {
$i++;
}
}
return [$less, $greater];
}
function quickSort3(array &$items, int $low, int $high, int &$count): void
{
if ($low >= $high) {
return;
}
[$less, $greater] = threeWay($items, $low, $high, $count);
quickSort3($items, $low, $less - 1, $count);
quickSort3($items, $greater + 1, $high, $count);
}
$grades = array_merge(
array_fill(0, 30, 5),
array_fill(0, 20, 3),
array_fill(0, 10, 4)
);
quickSort3($grades, 0, count($grades) - 1, $comparisons);
echo "order: ", implode(",", array_unique($grades)), "\n";
echo "comparisons: $comparisons\n";
threeWay keeps three regions: below $less are the smaller values, above $greater are the larger ones, and the part in between holds values equal to the pivot. The equal part is finished after one pass, so the recursion never sees it again. For 60 grades with three distinct values the whole sort needs 100 comparisons, a linear number that does not grow with the number of duplicates; a two-way partition would peel off one element per pass and take a quadratic number of comparisons.
$ php qs_three_way.php order: 3,4,5 comparisons: 100
When to use quick sort
Quick sort is a good general-purpose algorithm when the data fits in memory and the extra memory of a merge sort is unwanted.
- Average case: O(n log n) with a good pivot and no need for a second array.
- In-place sorting: the Lomuto version reuses the input array and keeps the extra space to the call stack.
- Repeated keys: use a three-way partition when the data has many equal values.
- Stability: quick sort is not stable; use merge sort when equal elements must keep their order.
- Everyday PHP: prefer
sortandusort, which are faster and stable.
Source
This article covered quick sort in PHP: the recursive idea, a simple implementation, the in-place Lomuto partition, comparison counts for sorted input with different pivots, and three-way partitioning for duplicate keys. See also the PHP merge sort, heap sort, counting sort, and bubble sort tutorials.
Author
List all PHP tutorials.