forked from arin2002/Hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.py
More file actions
36 lines (26 loc) · 728 Bytes
/
binary_search.py
File metadata and controls
36 lines (26 loc) · 728 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
from sorting import mergesort
def search(arr, item):
"""Performs binary search on an array
with the given item and returns True or
False.
>>> search([5, 4, 1, 6, 2, 3, 9, 7], 2)
True
>>> search([5, 4, 1, 6, 2, 3, 9, 7], 8)
False
"""
arr = mergesort(arr)
first = 0
last = len(arr) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if arr[midpoint] == item:
found = True
else:
if item < arr[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found
print search([5, 4, 1, 6, 2, 3, 9, 7], 2)
print search([5, 4, 1, 6, 2, 3, 9, 7], 8)