Created
May 13, 2015 10:34
-
-
Save josephok/7e78ed674f347202b5c6 to your computer and use it in GitHub Desktop.
quick sort in Javascript
This file contains hidden or 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 quickSort = function(arr) { | |
if (!Array.isArray(arr)) throw new Error("arguments should be an array"); | |
if (arr.length <= 1) { return arr; } | |
var pivotIndex = Math.floor(arr.length / 2); | |
var pivot = arr.splice(pivotIndex, 1)[0]; | |
var left = []; | |
var right = []; | |
for (var i = 0; i < arr.length; i++){ | |
if (arr[i] < pivot) { | |
left.push(arr[i]); | |
} else { | |
right.push(arr[i]); | |
} | |
} | |
return quickSort(left).concat([pivot], quickSort(right)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment