Last active
August 29, 2015 14:14
-
-
Save doron2402/a44890d3a1b6ee39e2e0 to your computer and use it in GitHub Desktop.
quick sort using javascript
This file contains 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
/* | |
Swap values using two index | |
@param items {Array} | |
@param firstIndex {Integer} | |
@param secondIndex {Integer} | |
@return 'undefined' | |
*/ | |
var swap = function(items, firstIndex, secondIndex){ | |
var temp = items[firstIndex]; | |
items[firstIndex] = items[secondIndex]; | |
items[secondIndex] = temp; | |
return; | |
}; | |
/* | |
partition | |
*/ | |
var partition = function(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; | |
}; | |
var quickSort = function(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 arrToSort = [65,43,12,4,564,32,-5,-202, 45]; | |
var result = quickSort(arrToSort, 0, arrToSort.length - 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment