Skip to content

Instantly share code, notes, and snippets.

@sugendran
Created May 29, 2012 23: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 sugendran/2831514 to your computer and use it in GitHub Desktop.
Save sugendran/2831514 to your computer and use it in GitHub Desktop.
Add a binary find to underscorejs
// Binary find in a sorted array
// val can either be a value or a function that returns
// 1 == found, -1 for obj is less than val, 1 for obj is greater than val
_.bfind = function(array, val) {
if (!array.length) {
return null;
}
var iterator = _.isFunction(val) ? val : function(obj) {
return obj == val ? 0 : (obj < val ? -1 : 1);
};
var low = 0,
high = array.length - 1;
while (low < high) {
var mid = (low + high) >> 1;
var check = iterator(array[mid]);
if (check === 0) {
return array[mid];
}
if(check < 0) {
if(iterator(array[high]) == 0) {
return array[high];
}
low = mid + 1;
} else {
if(iterator(array[low]) == 0) {
return array[low];
}
high = mid;
}
}
if (iterator(array[low]) === 0) {
return array[low];
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment