-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearching_algorithms.py
51 lines (35 loc) · 1.22 KB
/
searching_algorithms.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
48
49
50
51
import numpy as np
import time
from Sorting_algorithms import merge_sort
def linear_search(array, value):
for index, item in enumerate(array):
if value == item:
return index, array[index]
return None, value
def binary_search(array, value):
left_index = 0
right_index = len(array) - 1
while left_index <= right_index:
mid_index = (left_index + right_index) // 2
if array[mid_index] == value:
return mid_index, array[mid_index]
elif array[mid_index] < value:
left_index = mid_index + 1
else:
right_index = mid_index - 1
return None, value
def time_it(begin, end):
return end - begin
if __name__ == "__main__":
array = [i for i in np.random.randint(0, 10000, 10000)]
sorted_array = merge_sort(array)
value = np.random.choice(array)
print(sorted_array)
start = time.time()
print(linear_search(array, value))
stop = time.time()
print('Time taken for linear search execution', time_it(start, stop), ' Seconds')
start = time.time()
print(binary_search(sorted_array, value))
stop = time.time()
print('Time taken for binary search execution', time_it(start, stop), ' Seconds')