Created
June 12, 2015 01:11
-
-
Save aweary/213e8e1c49fc7d188a42 to your computer and use it in GitHub Desktop.
binary.js
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
// Find the index of an element in an array using binary sorting | |
function binarySort(collection, target, callback, minimum, maximum) { | |
// Get the starting and ending points | |
var min = minimum || 0; | |
var max = maximum || collection.length; | |
// Get the median value and the value at that index | |
var median = Math.floor((min + max) / 2); | |
var result = collection[median]; | |
console.log('Min is %j, Max is %j, median is %j', min, max, median); | |
// If we've found our target, return the index | |
if (result === target) { | |
callback(median); | |
return; | |
} | |
// Otherwise, split the array one way or the other and recurse | |
else if (result > target) { | |
max = median; | |
console.log('%j greater than %j', result, target); | |
} | |
else if (result < target) { | |
min = median; | |
console.log('%j less than %j', result, target); | |
} | |
binarySort(collection, target, callback, min, max); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment