Skip to content

Instantly share code, notes, and snippets.

@zekrom-vale
Last active March 9, 2018 13:28
Show Gist options
  • Save zekrom-vale/45602c9ae65827e19764bec315916a6f to your computer and use it in GitHub Desktop.
Save zekrom-vale/45602c9ae65827e19764bec315916a6f to your computer and use it in GitHub Desktop.
Find if the value exists in a sorted array or return the index.
function binarySearch(l,v){
var m=0,M=l.length,g;
while(m<=M){
//bitwisecmd.com/#0xffffffff%3E%3E%3E1
if(M<=0xF0000000){
while(m<=M){
g=(M+m)>>>1;
if(l[g]===v)return g;
if (l[g]<v)m=g+1;
else M=g-1;
}
}else g=Math.floor((M+m)/2);
if(l[g]===v)return g;
if (l[g]<v)m=g+1;
else M=g-1;
}return -1;
}
function binaryExists(l,v){
var m=0,M=l.length,g;
while(m<=M){
if(M<=0xF0000000){
while(m<=M){
g=(M+m)>>>1;
if(l[g]===v)return true;
if (l[g]<v)m=g+1;
else M=g-1;
}
}else g=Math.floor((M+m)/2);
if(l[g]===v)return true;
if (l[g]<v)m=g+1;
else M=g-1;
}return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment