|
| 1 | +""" |
| 2 | +A recursive implementation of the insertion sort algorithm |
| 3 | +""" |
| 4 | + |
| 5 | +from typing import List |
| 6 | + |
| 7 | +def rec_insertion_sort(collection: List, n: int): |
| 8 | + """ |
| 9 | + Given a collection of numbers and its length, sorts the collections |
| 10 | + in ascending order |
| 11 | +
|
| 12 | + :param collection: A mutable collection of comparable elements |
| 13 | + :param n: The length of collections |
| 14 | +
|
| 15 | + >>> col = [1, 2, 1] |
| 16 | + >>> rec_insertion_sort(col, len(col)) |
| 17 | + >>> print(col) |
| 18 | + [1, 1, 2] |
| 19 | +
|
| 20 | + >>> col = [2, 1, 0, -1, -2] |
| 21 | + >>> rec_insertion_sort(col, len(col)) |
| 22 | + >>> print(col) |
| 23 | + [-2, -1, 0, 1, 2] |
| 24 | +
|
| 25 | + >>> col = [1] |
| 26 | + >>> rec_insertion_sort(col, len(col)) |
| 27 | + >>> print(col) |
| 28 | + [1] |
| 29 | + """ |
| 30 | + #Checks if the entire collection has been sorted |
| 31 | + if len(collection) <= 1 or n <= 1: |
| 32 | + return |
| 33 | + |
| 34 | + |
| 35 | + insert_next(collection, n-1) |
| 36 | + rec_insertion_sort(collection, n-1) |
| 37 | + |
| 38 | +def insert_next(collection: List, index: int): |
| 39 | + """ |
| 40 | + Inserts the '(index-1)th' element into place |
| 41 | +
|
| 42 | + >>> col = [3, 2, 4, 2] |
| 43 | + >>> insert_next(col, 1) |
| 44 | + >>> print(col) |
| 45 | + [2, 3, 4, 2] |
| 46 | +
|
| 47 | + >>> col = [3, 2, 3] |
| 48 | + >>> insert_next(col, 2) |
| 49 | + >>> print(col) |
| 50 | + [3, 2, 3] |
| 51 | +
|
| 52 | + >>> col = [] |
| 53 | + >>> insert_next(col, 1) |
| 54 | + >>> print(col) |
| 55 | + [] |
| 56 | + """ |
| 57 | + #Checks order between adjacent elements |
| 58 | + if index >= len(collection) or collection[index - 1] <= collection[index]: |
| 59 | + return |
| 60 | + |
| 61 | + #Swaps adjacent elements since they are not in ascending order |
| 62 | + collection[index - 1], collection[index] = ( |
| 63 | + collection[index], collection[index - 1] |
| 64 | + ) |
| 65 | + |
| 66 | + insert_next(collection, index + 1) |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + numbers = input("Enter integers seperated by spaces: ") |
| 70 | + numbers = [int(num) for num in numbers.split()] |
| 71 | + rec_insertion_sort(numbers, len(numbers)) |
| 72 | + print(numbers) |
0 commit comments