TheAlgorithms-Python
75 строк · 1.7 Кб
1"""
2A recursive implementation of the insertion sort algorithm
3"""
4
5from __future__ import annotations6
7
8def rec_insertion_sort(collection: list, n: int):9"""10Given a collection of numbers and its length, sorts the collections
11in ascending order
12
13:param collection: A mutable collection of comparable elements
14:param n: The length of collections
15
16>>> col = [1, 2, 1]
17>>> rec_insertion_sort(col, len(col))
18>>> col
19[1, 1, 2]
20
21>>> col = [2, 1, 0, -1, -2]
22>>> rec_insertion_sort(col, len(col))
23>>> col
24[-2, -1, 0, 1, 2]
25
26>>> col = [1]
27>>> rec_insertion_sort(col, len(col))
28>>> col
29[1]
30"""
31# Checks if the entire collection has been sorted32if len(collection) <= 1 or n <= 1:33return34
35insert_next(collection, n - 1)36rec_insertion_sort(collection, n - 1)37
38
39def insert_next(collection: list, index: int):40"""41Inserts the '(index-1)th' element into place
42
43>>> col = [3, 2, 4, 2]
44>>> insert_next(col, 1)
45>>> col
46[2, 3, 4, 2]
47
48>>> col = [3, 2, 3]
49>>> insert_next(col, 2)
50>>> col
51[3, 2, 3]
52
53>>> col = []
54>>> insert_next(col, 1)
55>>> col
56[]
57"""
58# Checks order between adjacent elements59if index >= len(collection) or collection[index - 1] <= collection[index]:60return61
62# Swaps adjacent elements since they are not in ascending order63collection[index - 1], collection[index] = (64collection[index],65collection[index - 1],66)67
68insert_next(collection, index + 1)69
70
71if __name__ == "__main__":72numbers = input("Enter integers separated by spaces: ")73number_list: list[int] = [int(num) for num in numbers.split()]74rec_insertion_sort(number_list, len(number_list))75print(number_list)76