Last active
October 18, 2020 15:16
-
-
Save Olical/5734530 to your computer and use it in GitHub Desktop.
JavaScript binary search with the same API as indexOf. Performance: http://jsperf.com/binaryindexof-and-indexof
This file contains 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
/** | |
* 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 = (minIndex + maxIndex) / 2 | 0; | |
currentElement = this[currentIndex]; | |
if (currentElement < searchElement) { | |
minIndex = currentIndex + 1; | |
} | |
else if (currentElement > searchElement) { | |
maxIndex = currentIndex - 1; | |
} | |
else { | |
return currentIndex; | |
} | |
} | |
return -1; | |
} |
This file contains 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
/** | |
* 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=(b+c)/2|0,d=this[a],d<e)b=a+1;else if(d>e)c=a-1;else return a;return-1}; |
@ftorre104 for some case that (mixIndex + maxIndex)
becomes into NaN
:
> NaN
NaN
> NaN / 2
NaN
> NaN / 2 | 0
0
just encure currentIndex
is a number.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey! Great code. Thanks.
Would you mind explaining
currentIndex = (minIndex + maxIndex) / 2 | 0
? I know you are dividing the range by 2, but what is the| 0
operation? Does that make it have 0 decimals or what?