-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbinary_index.py
More file actions
29 lines (26 loc) · 819 Bytes
/
binary_index.py
File metadata and controls
29 lines (26 loc) · 819 Bytes
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
def binary_index(alist, item):
first = 0
last = len(alist)-1
midpoint = 0
if(item< alist[first]):
return 0
while first<last:
midpoint = (first + last)//2
currentElement = alist[midpoint]
if currentElement < item:
if alist[midpoint+1] > item:
return midpoint
else: first = midpoint +1
if first == last and alist[last] > item:
return midpoint
elif currentElement > item:
last = midpoint -1
else:
if midpoint +1 ==len(alist):
return midpoint
while alist[midpoint+1] == item:
midpoint += 1
if midpoint + 1 == len(alist):
return midpoint
return midpoint
return last