Last active
December 20, 2015 09:39
-
-
Save eldilibra/6109280 to your computer and use it in GitHub Desktop.
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 quickSortNums (items) { | |
var sorted = []; | |
if (!(items instanceof Array)) { | |
throw new Error('The parameter must be an array.'); | |
} | |
if (items.length < 2) { | |
return items; | |
} | |
var pivot = items[Math.floor(items.length / 2)]; | |
sorted.push.apply(sorted, quickSortNums(filter(items, '_ < pivot', { pivot: pivot }))); | |
sorted.push.apply(sorted, filter(items, '_ === pivot', { pivot: pivot })); | |
sorted.push.apply(sorted, quickSortNums(filter(items, '_ > pivot', { pivot: pivot }))); | |
return sorted; | |
} | |
function filter (array, conditionString, contextObject) { | |
var result = []; | |
for (key in contextObject) { | |
eval(key + ' = ' + contextObject[key]); | |
} | |
array.forEach(function (_) { | |
eval('_ = ' + _); | |
if (eval(conditionString)) { | |
result.push(_); | |
} | |
}); | |
return result; | |
} | |
var test = [4, 5, 8, 2, 1, 0, 34, 233545, 13, 123, 33, 8, 45, 8.4, 123]; | |
console.log('TEST:', test); | |
console.log('RESULT:', quickSortNums(test)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Felt like trying a hybrid-style quicksort implentation. Yes, I used eval; I know. Anyway, this was inspired by some Scala I've been reading lately.