Created
January 14, 2014 16:04
-
-
Save motiooon/8420731 to your computer and use it in GitHub Desktop.
QuickSort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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