Pure implementation of the insertion sort algorithm in Python :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)
| 13 | |
| 14 | |
| 15 | def insertion_sort(collection): |
| 16 | """Pure implementation of the insertion sort algorithm in Python |
| 17 | |
| 18 | :param collection: some mutable ordered collection with heterogeneous |
| 19 | comparable items inside |
| 20 | :return: the same collection ordered by ascending |
| 21 | |
| 22 | Examples: |
| 23 | >>> insertion_sort([0, 5, 3, 2, 2]) |
| 24 | [0, 2, 2, 3, 5] |
| 25 | |
| 26 | >>> insertion_sort([]) |
| 27 | [] |
| 28 | |
| 29 | >>> insertion_sort([-2, -5, -45]) |
| 30 | [-45, -5, -2] |
| 31 | """ |
| 32 | for index in range(1, len(collection)): |
| 33 | while index > 0 and collection[index - 1] > collection[index]: |
| 34 | collection[index], collection[index - 1] = collection[index - 1], collection[index] |
| 35 | index -= 1 |
| 36 | |
| 37 | return collection |
| 38 | |
| 39 | |
| 40 | if __name__ == '__main__': |
no outgoing calls
no test coverage detected