Skip to content

Instantly share code, notes, and snippets.

@hackerrdave
Created August 12, 2018 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hackerrdave/02f87fbcf638de925b16893767261f54 to your computer and use it in GitHub Desktop.
Save hackerrdave/02f87fbcf638de925b16893767261f54 to your computer and use it in GitHub Desktop.
Algorithms | Quick Sort | JavaScript
// Quick Sort Algorithm implemented in JavaScript
// By @hackerrdave
function quickSort(arr) {
if (arr.length < 2) {
return arr;
}
let pivot = arr[0]; //let pivot point be the first element
let lesser = []; //track elements < the pivot value
let greater = []; //track elements greater >= the pivot value
for (let i = 1; i < arr.length; i++) {
if (arr[i] < pivot) {
lesser.push(arr[i]);
} else {
greater.push(arr[i]);
}
}
//recurse into lesser and greater collections, setting up
//new pivots and lesser/greater collections. After bubbling
//back up concat the lesser singular-array value with the pivot
//and greater singular-value array
return quickSort(lesser).concat(pivot, quickSort(greater));
}
//usage:
quickSort([4,2,8,3,6,9,1]); //=> [1,2,3,4,6,8,9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment