2020-01-13 16:22:18 +00:00
|
|
|
"""
|
|
|
|
A recursive implementation of the insertion sort algorithm
|
|
|
|
"""
|
|
|
|
|
2020-09-23 11:30:13 +00:00
|
|
|
from __future__ import annotations
|
2020-01-13 16:22:18 +00:00
|
|
|
|
2020-01-13 18:56:06 +00:00
|
|
|
|
2020-09-23 11:30:13 +00:00
|
|
|
def rec_insertion_sort(collection: list, n: int):
|
2020-01-13 16:22:18 +00:00
|
|
|
"""
|
|
|
|
Given a collection of numbers and its length, sorts the collections
|
|
|
|
in ascending order
|
|
|
|
|
|
|
|
:param collection: A mutable collection of comparable elements
|
|
|
|
:param n: The length of collections
|
|
|
|
|
|
|
|
>>> col = [1, 2, 1]
|
|
|
|
>>> rec_insertion_sort(col, len(col))
|
|
|
|
>>> print(col)
|
|
|
|
[1, 1, 2]
|
|
|
|
|
|
|
|
>>> col = [2, 1, 0, -1, -2]
|
|
|
|
>>> rec_insertion_sort(col, len(col))
|
|
|
|
>>> print(col)
|
|
|
|
[-2, -1, 0, 1, 2]
|
|
|
|
|
|
|
|
>>> col = [1]
|
|
|
|
>>> rec_insertion_sort(col, len(col))
|
|
|
|
>>> print(col)
|
|
|
|
[1]
|
|
|
|
"""
|
2020-01-13 18:56:06 +00:00
|
|
|
# Checks if the entire collection has been sorted
|
2020-01-13 16:22:18 +00:00
|
|
|
if len(collection) <= 1 or n <= 1:
|
|
|
|
return
|
|
|
|
|
2020-01-13 18:56:06 +00:00
|
|
|
insert_next(collection, n - 1)
|
|
|
|
rec_insertion_sort(collection, n - 1)
|
2020-01-13 16:22:18 +00:00
|
|
|
|
|
|
|
|
2020-09-23 11:30:13 +00:00
|
|
|
def insert_next(collection: list, index: int):
|
2020-01-13 16:22:18 +00:00
|
|
|
"""
|
|
|
|
Inserts the '(index-1)th' element into place
|
|
|
|
|
|
|
|
>>> col = [3, 2, 4, 2]
|
|
|
|
>>> insert_next(col, 1)
|
|
|
|
>>> print(col)
|
|
|
|
[2, 3, 4, 2]
|
|
|
|
|
|
|
|
>>> col = [3, 2, 3]
|
|
|
|
>>> insert_next(col, 2)
|
|
|
|
>>> print(col)
|
|
|
|
[3, 2, 3]
|
|
|
|
|
|
|
|
>>> col = []
|
|
|
|
>>> insert_next(col, 1)
|
|
|
|
>>> print(col)
|
|
|
|
[]
|
|
|
|
"""
|
2020-01-13 18:56:06 +00:00
|
|
|
# Checks order between adjacent elements
|
2020-01-13 16:22:18 +00:00
|
|
|
if index >= len(collection) or collection[index - 1] <= collection[index]:
|
|
|
|
return
|
|
|
|
|
2020-01-13 18:56:06 +00:00
|
|
|
# Swaps adjacent elements since they are not in ascending order
|
2020-01-13 16:22:18 +00:00
|
|
|
collection[index - 1], collection[index] = (
|
2020-01-13 18:56:06 +00:00
|
|
|
collection[index],
|
|
|
|
collection[index - 1],
|
2020-01-13 16:22:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
insert_next(collection, index + 1)
|
|
|
|
|
2020-01-13 18:56:06 +00:00
|
|
|
|
2020-01-13 16:22:18 +00:00
|
|
|
if __name__ == "__main__":
|
2020-01-18 12:24:33 +00:00
|
|
|
numbers = input("Enter integers separated by spaces: ")
|
2020-01-13 16:22:18 +00:00
|
|
|
numbers = [int(num) for num in numbers.split()]
|
|
|
|
rec_insertion_sort(numbers, len(numbers))
|
|
|
|
print(numbers)
|