-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary_search.py
More file actions
36 lines (29 loc) · 771 Bytes
/
binary_search.py
File metadata and controls
36 lines (29 loc) · 771 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
import random
from quicksort import quicksort
def random_list():
lis = []
for i in range(10):
lis.append(random.randint(0,40))
return lis
def binary_search(numbers, target):
first = 0
last = len(numbers) - 1
while first <= last:
mid = (first + last) //2
if numbers[mid] == target:
return mid
elif numbers[mid] < target:
first = mid + 1
else:
last = mid - 1
return None
def verify(index):
if index is not None:
print(f'target found at index {index}')
else:
print('target not found in list')
numbers = random_list() # not ordered list
numbers = quicksort(numbers)
result = binary_search(numbers,32)
verify(result)
print(numbers)