Skip to content

Instantly share code, notes, and snippets.

@padolsey
Created December 3, 2009 02:45
Show Gist options
  • Select an option

  • Save padolsey/247839 to your computer and use it in GitHub Desktop.

Select an option

Save padolsey/247839 to your computer and use it in GitHub Desktop.
// @author James Padolsey
// originally posted @ http://stackoverflow.com/questions/1837056
Array.prototype.binarySearch = function(v) {
/* ARRAY MUST BE SORTED */
if ( !this.length ) { return false; }
if ( this[0] === v ) { return true; }
var i, mid,
start = 0,
end = this.length,
c = false;
while ( c = (i = this[mid = start+((end-start)>>1)]) !== v ) {
i < v ? (start = mid) : (end = mid);
if (start >= end - 1) { break; }
}
return !c;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment