Skip to content

Instantly share code, notes, and snippets.

@karuna24s
Last active January 16, 2020 16:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save karuna24s/2d81b2b38cf6f8dac003f9f148830f79 to your computer and use it in GitHub Desktop.
Save karuna24s/2d81b2b38cf6f8dac003f9f148830f79 to your computer and use it in GitHub Desktop.
// 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 ]
@roblevintennis
Copy link

Clever to use array.slice to preserve original array 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment