Skip to content

Instantly share code, notes, and snippets.

@dexteryy
Created April 20, 2010 17:07
Show Gist options
  • Save dexteryy/372753 to your computer and use it in GitHub Desktop.
Save dexteryy/372753 to your computer and use it in GitHub Desktop.
# 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