Skip to content

Instantly share code, notes, and snippets.

@alepeino
Created March 1, 2017 18:23
Show Gist options
  • Save alepeino/80909b7bfd53ab95c7c31b968b4d9722 to your computer and use it in GitHub Desktop.
Save alepeino/80909b7bfd53ab95c7c31b968b4d9722 to your computer and use it in GitHub Desktop.
quicksort
function quicksort(arr, comp0) {
if (arr.length <= 1) {
return arr;
}
const comp = comp0 ? comp0 : (a, b) => parseInt(a) - parseInt(b);
const pivot = arr[0];
const higher = [];
const lower = [];
arr.slice(1).forEach(val => (comp(val, pivot) > 0) ? higher.push(val) : lower.push(val));
return [
...quicksort(lower, comp),
pivot,
...quicksort(higher,comp)
];
}
function quicksort(array $arr, callable $comp = null)
{
if (count($arr) <= 1) {
return $arr;
}
$comp = $comp ?: function ($a, $b) {
return intval($a) - intval($b);
};
$pivot = $arr[0];
$lower = $higher = [];
foreach (array_slice($arr, 1) as $val) {
if ($comp($pivot, $val) > 0) {
$lower[] = $val;
} else {
$higher[] = $val;
}
}
return array_merge(
quicksort($lower, $comp),
[$pivot],
quicksort($higher, $comp)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment