forked from princekumar-code/HacktoberFest2020-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary.py
More file actions
43 lines (21 loc) · 665 Bytes
/
Binary.py
File metadata and controls
43 lines (21 loc) · 665 Bytes
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
def search_binary(sorted_array, target):
left = 0
right = len(sorted_array) - 1
while left <= right:
midpoint = left + (right - left) // 2
current = sorted_array[midpoint]
if current == target:
return midpoint
else:
if target < current:
right = midpoint - 1
else:
left = midpoint + 1
return None
target = 5
sorted_array = [0, 1, 2, 3, 4, 5]
result = search_binary(sorted_array, target)
if result is not None:
print('Value {} found at position {} using binary search'.format(target, result+1))
else:
print('Not found')