-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinsert_sort.py
More file actions
38 lines (33 loc) · 764 Bytes
/
Copy pathinsert_sort.py
File metadata and controls
38 lines (33 loc) · 764 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
import time
def insert_sort(lst):
"""
best: O(n)
worst: O(n^2)
stable
"""
n = len(lst)
for i in range(1, n):
for j in range(i - 1, -1, -1):
if lst[j + 1] < lst[j]:
lst[j + 1], lst[j] = lst[j], lst[j + 1]
else:
break
def insert_sort_better(lst):
"""
best: O(n)
worst: O(n^2)
stable
"""
for i in range(1, len(lst)):
cur = lst[i]
j = i
while j > 0 and lst[j - 1] > cur:
lst[j] = lst[j - 1]
j -= 1
lst[j] = cur
if __name__ == "__main__":
st = time.time()
for _ in range(10000):
lst = [5, 4, 7, 1, 12, 13, 23, 0, 4]
insert_sort_better(lst)
print(time.time() - st)