Created
April 20, 2010 17:07
-
-
Save dexteryy/372753 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
# python版二分法: | |
import random, math | |
def bsearch(v, data, pre=0): | |
l = len(data) | |
if l <= 0: | |
return -1; | |
half = int(math.floor(l/2)) | |
c = v - data[half] | |
if c > 0: | |
return bsearch(v, data[half + 1:], pre + half + 1) | |
elif c < 0: | |
return bsearch(v, data[:half], pre) | |
else: | |
return pre + half | |
def main(): | |
DATA = range(0, 100, 2) | |
target = DATA[random.randint(0, len(DATA))] | |
print bsearch(target, DATA) | |
print bsearch(0, [0,1,2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment