forked from codebasics/data-structures-algorithms-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.py
More file actions
55 lines (41 loc) · 1.5 KB
/
binarysearch.py
File metadata and controls
55 lines (41 loc) · 1.5 KB
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
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
if mid_index >= len(numbers_list) or mid_index < 0:
return -1
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))
print(f"Number found at index {index} using binary search")