Created
February 10, 2020 16:51
-
-
Save sebinsua/c276318ea96595f8bb62715f23075e06 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env node | |
function quickSort(arr) { | |
if (arr.length <= 1) { | |
return arr; | |
} | |
// Choosing the first item as the pivot causes worst-case | |
// performance if an array is already sorted. | |
let randomIdx = Math.floor(Math.random() * arr.length); | |
let pivot = arr[randomIdx]; | |
let rest = [...arr]; | |
rest.splice(randomIdx, 1); | |
let left = rest.filter(i => i < pivot); | |
let right = rest.filter(i => i >= pivot); | |
return [...quickSort(left), pivot, ...quickSort(right)]; | |
} | |
console.log( | |
quickSort([ | |
8, | |
99, | |
998, | |
17, | |
10, | |
68, | |
2, | |
10021, | |
6, | |
2, | |
4, | |
234, | |
9, | |
456, | |
1, | |
2, | |
3, | |
9, | |
7, | |
5, | |
9, | |
3, | |
6, | |
5 | |
]) | |
); |
I should really try to implement an imperative
quickSort
that operates upon the array in-place.
https://gist.github.com/sebinsua/5f5ec07282bcee43f7df3c4396bdfaa5
three years later!!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I should really try to implement an imperative
quickSort
that operates upon the array in-place.