Created
December 5, 2016 11:58
-
-
Save jasonwilliams/31a44a6ff8d1b215d54314592df6d530 to your computer and use it in GitHub Desktop.
Easier, faster quicksort in 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
// var arr = [1,3,5,2,80,3,71,12]; | |
function sort(arr) { | |
// base case | |
if (arr.length <= 1) return arr; | |
var swapPos = Math.floor((arr.length - 1) / 2), | |
swapVal = arr[swapPos], less = [], more = []; | |
arr = arr.slice(0, swapPos).concat(arr.slice(swapPos + 1)); | |
arr.forEach(function(v, i, array) { | |
if (array[i] < swapVal) { | |
less.push(array[i]); | |
} else { | |
more.push(array[i]); | |
} | |
}); | |
return sort(less).concat([swapVal], sort(more)); | |
} | |
// console.log(sort(arr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment