-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSort.py
More file actions
67 lines (49 loc) · 1.35 KB
/
insertionSort.py
File metadata and controls
67 lines (49 loc) · 1.35 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
56
57
58
59
60
61
62
63
64
65
66
67
"""
Lecture 3: Insertion Sort & Merge Sort
Insertion Sort
- Time Complexity: 𝛩(n^2)
- Space Complexity: 𝛩(1)
"""
from typing import List
def insertion_sort(arr: List[int]) -> List[int]:
"""
𝛩(n^2) Compares, 𝛩(n^2) Swaps
"""
for i in range(1, len(arr)):
for j in range(i):
if arr[i - j] < arr[i - j - 1]:
arr[i - j], arr[i - j - 1] = arr[i - j - 1], arr[i - j]
return arr
def bianry_insertion_sort(arr: List[int]) -> List[int]:
"""
- 𝛩(nlogn) Compares, 𝛩(n^2) Swaps
"""
for i in range(1, len(arr)):
key = arr[i]
swap_index = binary_search(arr[:i], 0, i, key)
del arr[i]
arr.insert(swap_index, key)
return arr
def binary_search(arr, low, high, key):
if high - low == 1:
if arr[low] < key:
return high
else:
return low
else:
mid = (high + low) // 2
if arr[mid] == key:
return mid
elif arr[mid] > key:
return binary_search(arr, low, mid, key)
else:
return binary_search(arr, mid, high, key)
def main():
arr = [1, 5, 2, 6, 3, 7, 4]
for _ in range(5):
arr.extend(arr)
print(insertion_sort(arr))
# print(bianry_insertion_sort(arr))
if __name__ == "__main__":
import profile
profile.run("main()")