-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathinsertion_sort.py
45 lines (37 loc) · 1.09 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
#!/usr/bin/python
"""
Date: 2018-09-08
Description:
Implement insertion sort.
Approach:
Scans from right in sorted sub-array and inserts current element at correct
place by shifting all the elements to right.
Complexity:
O(n^2)
"""
def insertion_sort_increasing(A):
for i in range(1, len(A)):
key = A[i]
j = i
while j > 0 and A[j - 1] > key:
A[j] = A[j - 1]
j -= 1
A[j] = key # Insert current element at correct place.
def insertion_sort_descending(A):
for i in range(1, len(A)): # Fisrt element is sorted in itself
key = A[i]
j = i
while j and A[j - 1] < key:
A[j] = A[j - 1]
j -= 1
A[j] = key # Insert current element at correct place.
def sort(A):
B = A[:]
insertion_sort_increasing(A)
insertion_sort_descending(B)
return (A, B)
assert sort([3, 4, 5, 2, 1]) == ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1])
assert sort([3, 4, 5, 2, 1, 6]) == ([1, 2, 3, 4, 5, 6], [6, 5, 4, 3, 2, 1])
assert sort([]) == ([], [])
assert sort([1]) == ([1], [1])
assert sort([2, 1]) == ([1, 2], [2, 1])