-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_2_binary_search_with_time.py
More file actions
41 lines (34 loc) · 997 Bytes
/
Copy path1_2_binary_search_with_time.py
File metadata and controls
41 lines (34 loc) · 997 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
# -*- coding: utf-8 -*-
"""1.2.Binary Search With Time.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1OrKP5NApLuYquivMf2YDMyA5swMg6-Uz
"""
import time
import random
import matplotlib.pyplot as plt
def binary_search(arr, low, high, key):
if high >= low:
mid = (low + high) // 2
if arr[mid] == key:
return mid
elif arr[mid] > key:
return binary_search(arr, low, mid-1, key)
else:
return binary_search(arr, mid+1, high, key)
return -1
sizes = [100, 500, 1000, 5000, 10000]
times = []
for size in sizes:
arr = sorted(random.sample(range(size*10), size))
key = arr[-1]
start = time.time()
binary_search(arr, 0, len(arr)-1, key)
end = time.time()
times.append(end - start)
plt.plot(sizes, times, marker='x')
plt.xlabel("Number of Elements (n)")
plt.ylabel("Time (s)")
plt.title("Binary Search Time vs n")
plt.grid(True)
plt.show()