-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary search algotithm.py
47 lines (34 loc) · 1.19 KB
/
Binary search algotithm.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
# Function to determine if a `target` exists in the sorted list `nums`
# or not using a binary search algorithm
def binarySearch(nums, target):
# search space is nums[left…right]
(left, right) = (0, len(nums) - 1)
# loop till the search space is exhausted
while left <= right:
# find the mid-value in the search space and
# compares it with the target
mid = (left + right) // 2
# overflow can happen. Use:
# mid = left + (right - left) / 2
# mid = right - (right - left) // 2
# target is found
if target == nums[mid]:
return mid
# discard all elements in the right search space,
# including the middle element
elif target < nums[mid]:
right = mid - 1
# discard all elements in the left search space,
# including the middle element
else:
left = mid + 1
# `target` doesn't exist in the list
return -1
if __name__ == '__main__':
nums = [2, 5, 6, 8, 9, 10]
target = 5
index = binarySearch(nums, target)
if index != -1:
print('Element found at index', index)
else:
print('Element found not in the list')