Skip to content

Instantly share code, notes, and snippets.

@eldilibra
Last active December 20, 2015 09:39
Show Gist options
  • Save eldilibra/6109280 to your computer and use it in GitHub Desktop.
Save eldilibra/6109280 to your computer and use it in GitHub Desktop.
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));
@eldilibra
Copy link
Author

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.

@jonjohnjohnson
Copy link

Interesante...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment