-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSort-py
More file actions
55 lines (39 loc) · 1.11 KB
/
insertionSort-py
File metadata and controls
55 lines (39 loc) · 1.11 KB
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
52
53
54
55
import random
import time
import matplotlib.pyplot as plt
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j = j - 1
arr[j+1] = key
sizes = []
actual_times = []
theoretical_times = []
# create file
file = open("i_time.txt", "w")
for n in range(100, 10001, 400):
arr = [random.randint(0,10000) for _ in range(n)]
start = time.time()
insertion_sort(arr)
end = time.time()
actual_time = end - start
theoretical_time = (n*n) * 1e-8
sizes.append(n)
actual_times.append(actual_time)
theoretical_times.append(theoretical_time)
# write data to file
file.write(f"{n} {actual_time:.6f} {theoretical_time:.6f}\n")
file.close()
plt.plot(sizes, actual_times, marker='o', label="Actual Time")
plt.plot(sizes, theoretical_times, label="Theoretical O(n²)")
plt.title("Insertion Sort Time Efficiency (Python)")
plt.xlabel("Input Size")
plt.ylabel("Time (seconds)")
plt.legend()
plt.grid(True)
plt.savefig("insertion_python_graph.png")
plt.show()