Skip to content

Instantly share code, notes, and snippets.

@alvan
Last active August 29, 2015 14:04
Show Gist options
  • Save alvan/a02731e83c880366be23 to your computer and use it in GitHub Desktop.
Save alvan/a02731e83c880366be23 to your computer and use it in GitHub Desktop.
quicksort(Jon Bently<Beautiful code>)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
function quicksort(&$a, $l, $r)
{
if ($l >= $r) return;
/**
* {a}. item($a[$l]) is the pivot;
* {b}. items($a[$l+1, $m]) are all less than the pivot($a[$l]);
* {c}. if the item($a[$i], from $a[$l+1] to $a[$r]) is less than pivot($a[$l]), swap $a[++$m] and $a[$i],
* to make sure {b} is always true.
* {d}. last, swap $a[$l] and $a[$m], to make $a[$m] to be the pivot, and now:
* items($a[$l, $m-1]) are all less than the pivot($a[$m]),
* items($a[$m+1, $r]) are all greater than the pivot($a[$m]).
*/
$m = $l;
for ($i = $l + 1; $i <= $r; $i++)
{
if ($a[$i] < $a[$l])
{
++$m;
list($a[$m], $a[$i]) = array($a[$i], $a[$m]);
}
}
list($a[$m], $a[$l]) = array($a[$l], $a[$m]);
quicksort($a, $l, $m - 1);
quicksort($a, $m + 1, $r);
}
$a = range(1, 10);
shuffle($a);
print_r($a);
quicksort($a, 0, count($a) - 1);
print_r($a);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment