Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending >>> shell_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> shell_sort([]) []
(collection: list[int])
| 4 | |
| 5 | |
| 6 | def shell_sort(collection: list[int]) -> list[int]: |
| 7 | """Pure implementation of shell sort algorithm in Python |
| 8 | :param collection: Some mutable ordered collection with heterogeneous |
| 9 | comparable items inside |
| 10 | :return: the same collection ordered by ascending |
| 11 | |
| 12 | >>> shell_sort([0, 5, 3, 2, 2]) |
| 13 | [0, 2, 2, 3, 5] |
| 14 | >>> shell_sort([]) |
| 15 | [] |
| 16 | >>> shell_sort([-2, -5, -45]) |
| 17 | [-45, -5, -2] |
| 18 | """ |
| 19 | # Marcin Ciura's gap sequence |
| 20 | |
| 21 | gaps = [701, 301, 132, 57, 23, 10, 4, 1] |
| 22 | for gap in gaps: |
| 23 | for i in range(gap, len(collection)): |
| 24 | insert_value = collection[i] |
| 25 | j = i |
| 26 | while j >= gap and collection[j - gap] > insert_value: |
| 27 | collection[j] = collection[j - gap] |
| 28 | j -= gap |
| 29 | if j != i: |
| 30 | collection[j] = insert_value |
| 31 | return collection |
| 32 | |
| 33 | |
| 34 | if __name__ == "__main__": |