-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathbinarysearch.py
54 lines (35 loc) · 1.34 KB
/
binarysearch.py
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
"""
Purpose of this is to find a target element in an already sorted list L.
We use the fact that it is already sorted and get a O(log(n)) search algorithm.
Programmed by Aladdin Persson <aladdin.persson at hotmail dot com>
# 2019-03-12 Initial programming
"""
def binarysearch_iterative(L, target):
low = 0
high = len(L) - 1
while low <= high:
middle = (low + high) // 2
if target == L[middle]:
return True, middle
elif target < L[middle]:
high = middle - 1
else:
low = middle + 1
return False, None
def binarysearch_recursive(L, target, low, high):
middle = (low + high) // 2
if low > high:
return False, None
elif target == L[middle]:
return True, middle
elif target < L[middle]:
return binarysearch_recursive(L, target, low, middle - 1)
else:
return binarysearch_recursive(L, target, middle + 1, high)
if __name__ == "__main__":
target = 1
sorted_array = [1, 1, 1, 1, 1, 1, 1, 1]
exists, idx = binarysearch_iterative(sorted_array, target)
print(f"The target {target} exists in array: {exists}. The idx of it is: {idx}")
exists, idx = binarysearch_recursive(sorted_array, target, 0, len(sorted_array) - 1)
print(f"The target {target} exists in array: {exists}. The idx of it is: {idx}")