-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathbinarysearch.py
52 lines (39 loc) · 1.43 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
from util import time_it
@time_it
def linear_search(numbers_list, number_to_find):
for index, element in enumerate(numbers_list):
if element == number_to_find:
return index
return -1
@time_it
def binary_search(numbers_list, number_to_find):
left_index = 0
right_index = len(numbers_list) - 1
mid_index = 0
while left_index <= right_index:
mid_index = (left_index + right_index) // 2
mid_number = numbers_list[mid_index]
if mid_number == number_to_find:
return mid_index
if mid_number < number_to_find:
left_index = mid_index + 1
else:
right_index = mid_index - 1
return -1
def binary_search_recursive(numbers_list, number_to_find, left_index, right_index):
if right_index < left_index:
return -1
mid_index = (left_index + right_index) // 2
mid_number = numbers_list[mid_index]
if mid_number == number_to_find:
return mid_index
if mid_number < number_to_find:
left_index = mid_index + 1
else:
right_index = mid_index - 1
return binary_search_recursive(numbers_list, number_to_find, left_index, right_index)
if __name__ == '__main__':
numbers_list = [12, 15, 17, 19, 21, 24, 45, 67]
number_to_find = 21
index = binary_search_recursive(numbers_list, number_to_find, 0, len(numbers_list)-1)
print(f"Number found at index {index} using binary search")