Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Created February 10, 2020 16:51
Show Gist options
  • Save sebinsua/c276318ea96595f8bb62715f23075e06 to your computer and use it in GitHub Desktop.
Save sebinsua/c276318ea96595f8bb62715f23075e06 to your computer and use it in GitHub Desktop.
#!/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
])
);
@sebinsua
Copy link
Author

sebinsua commented Feb 10, 2020

I should really try to implement an imperative quickSort that operates upon the array in-place.

@sebinsua
Copy link
Author

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