-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinsertion_sort.py
More file actions
58 lines (49 loc) · 1.69 KB
/
Copy pathinsertion_sort.py
File metadata and controls
58 lines (49 loc) · 1.69 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
# Insertion sort (Ascending order)
def sortInsertionAsc(alist:list) -> None:
""" Apply insertion sort in ascending order on a list
:param alist: The list to be sorted
:type alist: list
"""
size = len(alist)
# sortedEnd runs from 0 to size-1
for sortedEnd in range(0, size):
toInsert = alist[sortedEnd]
# find suitable place to insert
insertLoc = 0
while insertLoc < sortedEnd:
if toInsert < alist[insertLoc]:
break
insertLoc += 1
# insertLoc is the location to insert
# right shift the remainng elements in the sorted part
for i in range(sortedEnd, insertLoc, -1):
alist[i] = alist[i-1]
alist[insertLoc] = toInsert
# print(alist)
# Insertion sort (Descending order)
def sortInsertionDesc(alist:list) -> None:
"""Apply insertion sort in decending order on a list
:param alist: The list to be sorted
:type alist: list
"""
size = len(alist)
# sortedEnd runs from 0 to size-1
for sortedEnd in range(0, size):
toInsert = alist[sortedEnd]
# find suitable place to insert
insertLoc = 0
while insertLoc < sortedEnd:
if toInsert > alist[insertLoc]:
break
insertLoc += 1
# insertLoc is the location to insert
# right shift the remainng elements in the sorted part
for i in range(sortedEnd, insertLoc, -1):
alist[i] = alist[i-1]
alist[insertLoc] = toInsert
if __name__ == "__main__":
numlist = [20, 14, 36, 8, 56, 49]
sortInsertionAsc(numlist)
print(numlist)
sortInsertionDesc(numlist)
print(numlist)