Skip to content

Instantly share code, notes, and snippets.

@SamChristy
Created January 20, 2012 20:38
Show Gist options
  • Select an option

  • Save SamChristy/1649430 to your computer and use it in GitHub Desktop.

Select an option

Save SamChristy/1649430 to your computer and use it in GitHub Desktop.
Super fast, iterative binary search. For those of you who are fed up with indexOf!
/**
* Searches the specified range of a sorted array for a given value; if the
* wanted value is found, its index is returned. -1 is returned if the item
* is not found. If no range is specified, the entire array will be searched.
* Please note: the array that this method is invoked on must be sorted in
* ascending order!
* @param {int|float|string} wanted The value to be searched for.
* @param {int} [first] The start of the search range.
* @param {int} [last] The end of the search range.
* @return {int} The index of the element if found, otherwise -1.
*/
Array.prototype.binarySearch = function(wanted, first, last)
{
//if(typeof wanted !== typeof this[0])
if(wanted == null)
return -1 // Searching for nothing may introduce an infinite loop.
if(first == null)
var first = 0;
if(last == null)
var last = this.length - 1;
else if(last < 0)
last += this.length;
while(first <= last)
{
var middle = Math.floor((first + last) / 2);
if(wanted < this[middle])
last = middle - 1;
else if(wanted > this[middle])
first = middle + 1;
else // We've found her!
return middle;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment