Last active
August 29, 2015 14:21
-
-
Save louisbros/9e7d0b3fc7e802f3b2bf to your computer and use it in GitHub Desktop.
JavaScript QuickSort Impl
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
function getRandomNumber(min, max) { | |
return Math.round(Math.random() * (max - min) + min); | |
} | |
function lessThan(a, b) { | |
return a < b; | |
} | |
function comparator(predicate) { | |
return function (a, b) { | |
if (predicate(a, b)) { | |
return -1; | |
} else if (predicate(b, a)) { | |
return 1; | |
} else { | |
return 0; | |
} | |
} | |
} | |
function swap(list, a, b) { | |
var temp = list[a]; | |
list[a] = list[b]; | |
list[b] = temp; | |
} | |
function middle(lo, hi) { | |
return Math.floor((hi + lo) / 2); | |
} | |
function partition(list, comparator, lo, hi) { | |
var pivot = list[middle(lo, hi)]; | |
while (lo <= hi) { | |
while (comparator(list[lo], pivot) < 0) lo++; | |
while (comparator(list[hi], pivot) > 0) hi--; | |
if (lo <= hi) { | |
swap(list, lo++, hi--); | |
} | |
} | |
return lo; | |
} | |
function quickSort(list, comparator) { | |
function _quickSort(result, comparator, lo, hi) { | |
if (list.length > 1) { | |
var index = partition(result, comparator, lo, hi); | |
if (lo < index - 1) { | |
_quickSort(result, comparator, lo, index - 1, result); | |
} | |
if (index < hi) { | |
_quickSort(result, comparator, index, hi); | |
} | |
} | |
return result; | |
} | |
return _quickSort(list.slice(), comparator, 0, list.length - 1); | |
} | |
var list = _.range(50).map(function () { | |
return getRandomNumber(0, 100); | |
}); | |
console.clear(); | |
console.info('%c ' + list, 'color: red'); | |
console.time('quicksort'); | |
var result = quickSort(list, comparator(lessThan)); | |
console.timeEnd('quicksort'); | |
console.info('%c ' + result, 'color: green'); | |
console.time('sort'); | |
var result = list.sort(comparator(lessThan)); | |
console.timeEnd('sort'); | |
console.info('%c ' + result, 'color: green'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment