Created
May 29, 2012 23:47
-
-
Save sugendran/2831514 to your computer and use it in GitHub Desktop.
Add a binary find to underscorejs
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
// 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