Skip to content

Instantly share code, notes, and snippets.

@james-prado james-prado/quicksort.js
Last active Jan 25, 2017

Embed
What would you like to do?
QuickSort Recursive Function In JavasScript
function quickSort(numbers, target, partial) {
var sum, remaining;
var partial = partial || [];
// sum partial
sum = partial.reduce(function (a, b) {
return a + b;
}, 0);
// check if the sum partial equals the target
if (sum === target) {
console.log("%s=%s", partial.join("+"), target + ', Sum: ' + sum + ', Target: ' + target + ', Partial: ' + partial + ', Remaining: ' + numbers);
return;
} else if (sum > target) {
return // if we're past the target, there is no reason to continue
}
for (var i = 0; i < numbers.length; i++) {
number = numbers[i];
remaining = numbers.slice(i + 1);
quickSort(remaining, target, partial.concat([number]));
}
}
// Examples
quickSort([100, 50, 20, 10, 5, 1], 176);
quickSort([3, 9, 8, 4, 5, 7, 10], 15);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.