Skip to content

Instantly share code, notes, and snippets.

@aselbie
Last active August 29, 2015 14:03
Show Gist options
  • Save aselbie/bdc103ed4e33e4775b12 to your computer and use it in GitHub Desktop.
Save aselbie/bdc103ed4e33e4775b12 to your computer and use it in GitHub Desktop.
var quicksort = function(A) {
var swap = function(a, b) {
var temp = A[a];
A[a] = A[b];
A[b] = temp;
}
var partition = function(left, right) {
var pivotIndex = Math.floor((left + right) / 2);
var pivotValue = A[pivotIndex];
swap(pivotIndex, right);
var storeIndex = left;
for (var i = left; i < right; i++) {
if (A[i] <= pivotValue) {
swap(i, storeIndex);
storeIndex = storeIndex + 1;
}
};
swap(storeIndex, right);
return storeIndex;
}
var sort = function(i, k) {
if (i < k) {
var p = partition(i, k);
sort(i, p - 1);
sort(p + 1, k);
}
}
sort(0, A.length - 1);
return A;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment