Created
August 12, 2018 15:37
-
-
Save hackerrdave/02f87fbcf638de925b16893767261f54 to your computer and use it in GitHub Desktop.
Algorithms | Quick Sort | JavaScript
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
// 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