Created
April 20, 2010 17:06
-
-
Save dexteryy/372751 to your computer and use it in GitHub Desktop.
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
// javascript版二分法: | |
function bsearch(v, data, pre){ | |
pre = pre || 0; | |
var l = data.length, | |
half = Math.floor(l/2), | |
c = v - data[half]; | |
if (c > 0) | |
return bsearch(v, data.slice(half + 1), pre + half + 1); | |
else if (c < 0) | |
return bsearch(v, data.slice(0, half), pre); | |
else if (c == 0) | |
return pre + half; | |
return -1; | |
} | |
// bsearch(5, [1,2,3,4,5,6,7,8]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment