-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary search
More file actions
51 lines (41 loc) · 1.56 KB
/
Copy pathBinary search
File metadata and controls
51 lines (41 loc) · 1.56 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
# Recursive call using pointers
# We calculate the middle index from the pointers now
mid_idx = (left_pointer + right_pointer) // 2
mid_val = sorted_list[mid_idx]
if mid_val == target:
return mid_idx
if mid_val > target:
# we reduce the sub-list by passing in a new right_pointer
return binary_search(sorted_list, left_pointer, mid_idx, target)
if mid_val < target:
# we reduce the sub-list by passing in a new left_pointer
return binary_search(sorted_list, mid_idx + 1, right_pointer, target)
values = [77, 80, 102, 123, 288, 300, 540]
start_of_values = 0
end_of_values = len(values)
result = binary_search(values, start_of_values, end_of_values, 288)
print("element {0} is located at index {1}".format(288, result))
# Iterative approach
def binary_search(sorted_list, target):
left_pointer = 0
right_pointer = len(sorted_list)
# fill in the condition for the while loop
while left_pointer < right_pointer:
# calculate the middle index using the two pointers
mid_idx = (left_pointer + right_pointer) // 2
mid_val = sorted_list[mid_idx]
if mid_val == target:
return mid_idx
if target < mid_val:
# set the right_pointer to the appropriate value
right_pointer = mid_idx
if target > mid_val:
# set the left_pointer to the appropriate value
left_pointer = mid_idx + 1
return "Value not in list"
# test cases
print(binary_search([5,6,7,8,9], 9))
print(binary_search([5,6,7,8,9], 10))
print(binary_search([5,6,7,8,9], 8))
print(binary_search([5,6,7,8,9], 4))
print(binary_search([5,6,7,8,9], 6))