Created
March 1, 2017 18:23
-
-
Save alepeino/80909b7bfd53ab95c7c31b968b4d9722 to your computer and use it in GitHub Desktop.
quicksort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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