Last active
September 5, 2021 19:44
-
-
Save kangax/6c4407941d976fe00948 to your computer and use it in GitHub Desktop.
Haskell-inspired quick sort in ES6
This file contains hidden or 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
| quicksort :: (Ord a) => [a] -> [a] | |
| quicksort [] = [] | |
| quicksort (x:xs) = | |
| let smallerSorted = quicksort (filter (<=x) xs) | |
| biggerSorted = quicksort (filter (>x) xs) | |
| in smallerSorted ++ [x] ++ biggerSorted |
This file contains hidden or 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
| /* | |
| 1) passing array | |
| > quicksort([4,3,2,1]); // => [1,2,3,4] | |
| */ | |
| function quicksort(tail) { | |
| if (tail.length === 0) return []; | |
| let head = tail.splice(0, 1)[0]; | |
| return quicksort(tail.filter( _ => _ <= head)) | |
| .concat([head]) | |
| .concat(quicksort(tail.filter( _ => _ > head ))) | |
| } | |
| /* | |
| 2) via arguments | |
| > quicksort(4,3,2,1); // => [1,2,3,4] | |
| or: | |
| > quicksort(...[4,3,2,1]); // => [1,2,3,4] | |
| */ | |
| function quicksort(x, ...xs) { | |
| if (arguments.length === 0) return []; | |
| return quicksort(...xs.filter( _ => _ <= x)) | |
| .concat([x]) | |
| .concat(quicksort(...xs.filter( _ => _ > x ))) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.