Skip to content

Instantly share code, notes, and snippets.

@james-prado
Last active January 25, 2017 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james-prado/4fd222d65f93aa6fc62c452942c3b5b7 to your computer and use it in GitHub Desktop.
Save james-prado/4fd222d65f93aa6fc62c452942c3b5b7 to your computer and use it in GitHub Desktop.
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