Last active
January 16, 2020 16:41
-
-
Save karuna24s/2d81b2b38cf6f8dac003f9f148830f79 to your computer and use it in GitHub Desktop.
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
// Create an array to sort | |
var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 12, 8, 11]; | |
// Basic implementation (pivot is the first element of the array) | |
function quicksort(array) { | |
if (array.length == 0) return []; | |
var left = [], right = [], pivot = array[0]; | |
for (var i = 1; i < array.length; i++) { | |
if(array[i] < pivot) | |
left.push(array[i]) | |
else | |
right.push(array[i]); | |
} | |
return quicksort(left).concat(pivot, quicksort(right)); | |
} | |
console.log(quicksort(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Clever to use
array.slice
to preserve original array 👍