Created
March 20, 2017 11:36
-
-
Save vbarinov/686447c42e500233ba53e3ff41ad39b5 to your computer and use it in GitHub Desktop.
Quick sort 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
/** | |
* Quick sort algorithm | |
* Complexity: O(n log n) to O(n) - depends on a pivot selection | |
*/ | |
function quickSort(arr) { | |
var pivotIndex, | |
pivot, | |
left = [], | |
right = [], | |
len = arr.length; | |
if (len < 2) { | |
return arr; | |
} else { | |
pivotIndex = Math.floor(Math.random() * len); | |
pivot = arr[pivotIndex]; | |
// left from pivot | |
for (var i = 0; i < pivotIndex; i++) { | |
var elem = arr[i]; | |
if (elem > pivot) { | |
right.push(elem); | |
} else { | |
left.push(elem); | |
} | |
} | |
// right from pivot | |
for (var i = pivotIndex + 1; i < len; i++) { | |
var elem = arr[i]; | |
if (elem > pivot) { | |
right.push(elem); | |
} else { | |
left.push(elem); | |
} | |
} | |
return quickSort(left).concat(pivot, quickSort(right)); | |
} | |
} | |
// tests | |
console.log(quickSort([5, 4, 1, 6, 19])); // [1, 4, 5, 6, 19] | |
console.log(quickSort([5, 6, 1, 6, 19, 0, -15])); // [-15, 0, 1, 5, 6, 6, 19] | |
console.log(quickSort([5])); // [5] | |
console.log(quickSort([])); // [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment