-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbetter_binary_search.py
More file actions
55 lines (36 loc) · 1003 Bytes
/
better_binary_search.py
File metadata and controls
55 lines (36 loc) · 1003 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
Given a sorted array of integers, return the index of a target element in the
array. If the element is not in the array, return -1. Assume there are no
duplicates in the array.
>>> get_index([0, 20, 34, 60, 79, 80], 31)
-1
>>> get_index([0, 20, 34, 60, 79, 80], 100)
-1
>>> get_index([20, 34, 60, 79, 80], 0)
-1
>>> get_index([0, 20, 34, 60, 79, 80], 0)
0
>>> get_index([0, 20, 34, 60, 79, 80], 20)
1
>>> get_index([0, 20, 34, 60, 79, 80], 34)
2
>>> get_index([0, 20, 34, 60, 79, 80], 60)
3
>>> get_index([0, 20, 34, 60, 79, 80], 79)
4
>>> get_index([0, 20, 34, 60, 79, 80], 80)
5
"""
def get_index(arr, target):
lower = 0
upper = len(arr) - 1
result = -1
while lower <= upper and result == -1:
midpoint = lower + (upper - lower)/2
if target == arr[midpoint]:
result = midpoint
elif target < arr[midpoint]:
upper = midpoint - 1
elif target > arr[midpoint]:
lower = midpoint + 1
return result