Skip to content

Instantly share code, notes, and snippets.

@adnils
Created April 7, 2014 07:00
Show Gist options
  • Save adnils/10015843 to your computer and use it in GitHub Desktop.
Save adnils/10015843 to your computer and use it in GitHub Desktop.
quicksort
function quickSort(items, left, right) {
var index;
if (items.length > 1) {
left = typeof left != "number" ? 0 : left;
right = typeof right != "number" ? items.length - 1 : right;
index = partition(items, left, right);
if (left < index - 1) {
quickSort(items, left, index - 1);
}
console.log (items);
if (index < right) {
quickSort(items, index, right);
}
console.log (items);
}
return items;
}
function partition(items, left, right) {
var pivot = items[Math.floor((right + left) / 2)],
i = left,
j = right;
while (i <= j) {
while (items[i] < pivot) {
i++;
}
while (items[j] > pivot) {
j--;
}
if (i <= j) {
swap(items, i, j);
i++;
j--;
}
}
return i;
}
function swap(items, firstIndex, secondIndex){
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
// first call
var result = quickSort(items);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment