Skip to content

Instantly share code, notes, and snippets.

@ssnau
Created April 5, 2014 10:09
Show Gist options
  • Save ssnau/9989952 to your computer and use it in GitHub Desktop.
Save ssnau/9989952 to your computer and use it in GitHub Desktop.
qsort
function qsort(arr) {
partition(arr, 0, arr.length - 1);
}
function partition(arr, left, right) {
// check terminate
if (left >= right) return;
// select a pivot, for simplicity select the right most one
var pivot = arr[right];
var pos = left;
// loop, pos must be the index that arr[pos] >= pivot,
// and all the left side of arr[pos] arr <= pivot
// all the right side of arr[pos] >= pivot
for (var i = left; i < right; i++) {
if (arr[i] <= pivot) {
swap(arr, i, pos);
pos++;
}
}
swap(arr, right, pos);
partition(arr, left, pos - 1);
partition(arr, pos + 1, right);
}
function swap(arr, a, b) {
var temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
a = [3, 5, 7, 1, 99, 10, 23, 67];
qsort(a);
console.log(a);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment