Skip to content

Instantly share code, notes, and snippets.

@motiooon
Created January 14, 2014 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save motiooon/8420731 to your computer and use it in GitHub Desktop.
Save motiooon/8420731 to your computer and use it in GitHub Desktop.
QuickSort
function swap(items, firstIndex, secondIndex){
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
function partition(items, left, right){
var pointer = Math.floor((left+right)/2);
var i = left;
var j = right;
while(i<=j){
while(items[i] < items[pointer]) {
i++;
};
while(items[pointer] < items[j]) {
j--;
}
if(i <= j) {
swap(items, i, j);
i++;
j--;
}
}
return i;
}
function quickSort(items, left, right){
var index;
if(items.length > 1){
index = partition(items, left, right);
if(left < index-1){
quickSort(items, left, index-1);
};
if(index < right){
quickSort(items, index, right);
}
}
return items;
}
var arr = [4,2,6,5,3,9];
console.log("array", arr);
var result = quickSort(arr, 0, arr.length - 1);
console.log("sorted array", arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment