A pure Python implementation of the insertion sort algorithm :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>>
(collection: MutableSequence[T])
| 25 | |
| 26 | |
| 27 | def insertion_sort[T: Comparable](collection: MutableSequence[T]) -> MutableSequence[T]: |
| 28 | """A pure Python implementation of the insertion sort algorithm |
| 29 | |
| 30 | :param collection: some mutable ordered collection with heterogeneous |
| 31 | comparable items inside |
| 32 | :return: the same collection ordered by ascending |
| 33 | |
| 34 | Examples: |
| 35 | >>> insertion_sort([0, 5, 3, 2, 2]) |
| 36 | [0, 2, 2, 3, 5] |
| 37 | >>> insertion_sort([]) == sorted([]) |
| 38 | True |
| 39 | >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45]) |
| 40 | True |
| 41 | >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) |
| 42 | True |
| 43 | >>> import random |
| 44 | >>> collection = random.sample(range(-50, 50), 100) |
| 45 | >>> insertion_sort(collection) == sorted(collection) |
| 46 | True |
| 47 | >>> import string |
| 48 | >>> collection = random.choices(string.ascii_letters + string.digits, k=100) |
| 49 | >>> insertion_sort(collection) == sorted(collection) |
| 50 | True |
| 51 | """ |
| 52 | |
| 53 | for insert_index in range(1, len(collection)): |
| 54 | insert_value = collection[insert_index] |
| 55 | while insert_index > 0 and insert_value < collection[insert_index - 1]: |
| 56 | collection[insert_index] = collection[insert_index - 1] |
| 57 | insert_index -= 1 |
| 58 | collection[insert_index] = insert_value |
| 59 | return collection |
| 60 | |
| 61 | |
| 62 | if __name__ == "__main__": |