Skip to content

Commit baf7a8d

Browse files
committed
A recursive insertion sort
1 parent f9e1a16 commit baf7a8d

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

sorts/recursive_insertion_sort.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
A recursive implementation of the insertion sort algorithm
3+
"""
4+
5+
def rec_insertion_sort(collection, n):
6+
"""
7+
Given a collection of numbers and its length, sorts the collections
8+
in ascending order
9+
10+
:param collection: A mutable collection of heterogenous, comparable elements
11+
:param n: The length of collections
12+
13+
>>> col = [1, 2, 1]
14+
>>> rec_insertion_sort(col, len(col))
15+
>>> print(col)
16+
[1, 1, 2]
17+
18+
>>> col = [2, 1, 0, -1, -2]
19+
>>> rec_insertion_sort(col, len(col))
20+
>>> print(col)
21+
[-2, -1, 0, 1, 2]
22+
23+
>>> col = [1]
24+
>>> rec_insertion_sort(col, len(col))
25+
>>> print(col)
26+
[1]
27+
"""
28+
29+
30+
#Checks if the entire collection has been sorted
31+
if len(collection) <= 1 or n <= 1:
32+
return
33+
34+
35+
data_swap(collection, n-1)
36+
rec_insertion_sort(collection, n-1)
37+
38+
def data_swap(collection, index):
39+
40+
#Checks order between adjacent elements
41+
if index >= len(collection) or collection[index - 1] <= collection[index]:
42+
return
43+
44+
#Swaps adjacent elements since they are not in ascending order
45+
collection[index - 1], collection[index] = (
46+
collection[index], collection[index - 1]
47+
)
48+
49+
data_swap(collection, index + 1)
50+
51+
if __name__ == "__main__":
52+
numbers = input("Enter integers seperated by spaces: ")
53+
numbers = [int(num) for num in numbers.split()]
54+
rec_insertion_sort(numbers, len(numbers))
55+
print(numbers)

0 commit comments

Comments
 (0)