Skip to content

Instantly share code, notes, and snippets.

@aweary
Created June 12, 2015 01:11
Show Gist options
  • Save aweary/213e8e1c49fc7d188a42 to your computer and use it in GitHub Desktop.
Save aweary/213e8e1c49fc7d188a42 to your computer and use it in GitHub Desktop.
binary.js
// 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