Last active
March 9, 2018 13:28
-
-
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.
This file contains hidden or 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
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