Skip to content

Instantly share code, notes, and snippets.

@pid
Forked from Olical/binary-search.js
Created June 9, 2013 07:09
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 pid/5741377 to your computer and use it in GitHub Desktop.
Save pid/5741377 to your computer and use it in GitHub Desktop.
/**
* Performs a binary search on the host array. This method can either be
* injected into Array.prototype or called with a specified scope like this:
* binaryIndexOf.call(someArray, searchElement);
*
* @param {*} searchElement The item to search for within the array.
* @return {Number} The index of the element which defaults to -1 when not found.
*/
function binaryIndexOf(searchElement) {
'use strict';
var minIndex = 0;
var maxIndex = this.length - 1;
var currentIndex;
var currentElement;
while (minIndex <= maxIndex) {
currentIndex = Math.floor((minIndex + maxIndex) / 2);
currentElement = this[currentIndex];
if (currentElement < searchElement) {
minIndex = currentIndex + 1;
}
else if (currentElement > searchElement) {
maxIndex = currentIndex - 1;
}
else {
return currentIndex;
}
}
return -1;
}
/**
* Performs a binary search on the host array. This method can either be
* injected into Array.prototype or called with a specified scope like this:
* binaryIndexOf.call(someArray, searchElement);
*
* @param {*} e The item to search for within the array.
* @return {Number} The index of the element which defaults to -1 when not found.
*/
function s(e){for(var b=0,c=this.length-1,a,d;b<=c;)if(a=Math.floor((b+c)/2),d=this[a],d<e)b=a+1;else if(d>e)c=a-1;else return a;return-1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment