Last active
January 25, 2017 18:47
-
-
Save james-prado/4fd222d65f93aa6fc62c452942c3b5b7 to your computer and use it in GitHub Desktop.
QuickSort Recursive Function In JavasScript
This file contains hidden or 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 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