Quick Sort
See it animated in Zerethon Tools ↗Partition around a pivot (Lomuto scheme, last element) and sort each side — O(n log n) on average.
Implementations
Sign in to open in IDE
Sign in with your Zerethon account to create your own copy of this sample.
Files
# Quick Sort
Zerethon Official Sample `quick-sort`, version 1.2.0, PHP 8.4.
- `quick_sort.php` — the algorithm, as shown in Zerethon Tools
- `main.php` — entry file: a short demonstration
- `test_quick_sort.php` — checks; set it as the entry file to run them
This project is your own copy. Changing it never changes the official sample.
See the algorithm animated: https://tools.zerethon.com/quick-sort-visualizer
<?php
require __DIR__ . '/quick_sort.php';
$a = [38, 27, 43, 3, 9, 82, 10, 27];
echo 'Before: [' . implode(', ', $a) . "]\n";
$result = $a;
quick_sort($result);
echo 'After: [' . implode(', ', $result) . "]\n";
$expected = $a;
sort($expected);
echo 'Same as sort(): ' . ($result === $expected ? 'true' : 'false') . "\n";
<?php
// Quick Sort (Zerethon Official Sample: quick-sort 1.2.0).
// The algorithm as shown in Zerethon Tools.
function quick_sort(array &$a, int $lo = 0, ?int $hi = null): void {
if ($hi === null) $hi = count($a) - 1;
if ($lo >= $hi) return;
$pivot = $a[$hi];
$i = $lo;
for ($j = $lo; $j < $hi; $j++) {
if ($a[$j] < $pivot) {
[$a[$i], $a[$j]] = [$a[$j], $a[$i]];
$i++;
}
}
[$a[$i], $a[$hi]] = [$a[$hi], $a[$i]];
quick_sort($a, $lo, $i - 1);
quick_sort($a, $i + 1, $hi);
}
<?php
// Checks for quick_sort. To run them, set this file as the entry file
// (the ▶ button next to it in Files) and press Run.
require __DIR__ . '/quick_sort.php';
/** Deterministic pseudo-random integers in [-50, 49] (the same as the Python checks). */
function numbers(int $seed, int $count): array
{
$out = [];
for ($i = 0; $i < $count; $i++) {
$seed = ($seed * 1103515245 + 12345) % 2 ** 31;
$out[] = $seed % 100 - 50;
}
return $out;
}
$cases = [[], [1], [2, 1], [1, 2, 3], [3, 2, 1], [5, 1, 5, 1, 5], [-3, 0, -1, 2]];
foreach ([[1, 10], [2, 50], [3, 200]] as [$seed, $size]) {
$cases[] = numbers($seed, $size);
}
foreach ($cases as $a) {
$result = $a;
quick_sort($result);
$expected = $a;
sort($expected);
if ($result !== $expected) {
fwrite(STDERR, 'quick_sort([' . implode(', ', array_slice($a, 0, 6)) . "...]) is wrong\n");
exit(1);
}
}
echo 'All ' . count($cases) . " checks passed.\n";
Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Quick Sort Visualizer.