binsearch

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def binsearch(a, key):
left = 0
right = len(a) - 1
# [left, right) -> [left, middle) middle (middle, right]
while left <= right:
middle = (left + right) / 2
if a[middle] < key:
left = middle + 1
continue
if a[middle] > key:
right = middle - 1
continue
if a[middle] == key:
return middle
return None
def binsearch2(a, key):
left = 0
right = len(a)
# [left, right) -> [left, middle) [middle, right)
while left < right:
middle = (left + right) / 2
if a[middle] < key:
left = middle + 1
continue
if a[middle] > key:
right = middle
continue
if a[middle] == key:
return middle
return None
a = range(20)
for i in xrange(21):
print binsearch2(a, i)