-
Notifications
You must be signed in to change notification settings - Fork 43
/
insertion_sort.py
69 lines (49 loc) · 1.48 KB
/
insertion_sort.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#---------------------------------------------------------------
# INSERTION SORT
#---------------------------------------------------------------
# https://github.com/yennanliu/CS_basics/blob/master/doc/pic/insert_sort_1.jpg
# https://rust-algo.club/sorting/insertion_sort/index.html
"""
Step 1) start from i = 1, find idx on left side (i=0), and insert (make left array ordering)
Step 2) start from i = 2, find idx on left side (0 <= i <= 1), and insert (make left array ordering)
Step 3) start from i = 3, find idx on left side (0 <= i <= 2), and insert (make left array ordering)
.
.
.
Time complexity
Best O(n)
Average O(n^2)
Worst O(n^2)
Space complexity
Worst space O(1) auxiliary
"""
# V0
# V1 (gpt)
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Usage example
# arr = [12, 11, 13, 5, 6]
# insertion_sort(arr)
# print("Sorted array is:", arr)
# V2
# https://www.geeksforgeeks.org/python-program-for-insertion-sort/
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
# arr = [12, 11, 13, 5, 6]
# r = insertionSort(arr)
# print ("Sorted array is:", r)