Skip to content

Instantly share code, notes, and snippets.

@tsprates
Last active August 29, 2015 14:16
Show Gist options
  • Save tsprates/f5a4aecf8226d30e02c8 to your computer and use it in GitHub Desktop.
Save tsprates/f5a4aecf8226d30e02c8 to your computer and use it in GitHub Desktop.
Quicksort implementation in JS.
/**
* Quicksort implementation.
*
* @see {@link http://en.wikipedia.org/wiki/Quicksort}
* @param {array} arr
* @result {array} Sorted array
.*/
var quicksort = function(arr) {
function partition(arr, left, right) {
var pivot = arr[Math.floor((right + left) / 2)],
i = left,
j = right,
temp;
while (i <= j) {
while (arr[i] < pivot) i++;
while (arr[j] > pivot) j--;
if (i <= j) {
temp = arr[i];
arr[i] = arr[j];
arr[j]= temp;
i++;
j--;
}
}
if (i < right)
partition(arr, i, right);
if (j > left)
partition(arr, left, j);
return arr;
}
return partition(arr, 0, arr.length - 1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment