Pure implementation of the gnome sort algorithm in Python Take some mutable ordered collection with heterogeneous comparable items inside as arguments, return the same collection ordered by ascending. Examples: >>> gnome_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> gnome
(lst: list)
| 14 | |
| 15 | |
| 16 | def gnome_sort(lst: list) -> list: |
| 17 | """ |
| 18 | Pure implementation of the gnome sort algorithm in Python |
| 19 | |
| 20 | Take some mutable ordered collection with heterogeneous comparable items inside as |
| 21 | arguments, return the same collection ordered by ascending. |
| 22 | |
| 23 | Examples: |
| 24 | >>> gnome_sort([0, 5, 3, 2, 2]) |
| 25 | [0, 2, 2, 3, 5] |
| 26 | |
| 27 | >>> gnome_sort([]) |
| 28 | [] |
| 29 | |
| 30 | >>> gnome_sort([-2, -5, -45]) |
| 31 | [-45, -5, -2] |
| 32 | |
| 33 | >>> "".join(gnome_sort(list(set("Gnomes are stupid!")))) |
| 34 | ' !Gadeimnoprstu' |
| 35 | """ |
| 36 | if len(lst) <= 1: |
| 37 | return lst |
| 38 | |
| 39 | i = 1 |
| 40 | |
| 41 | while i < len(lst): |
| 42 | if lst[i - 1] <= lst[i]: |
| 43 | i += 1 |
| 44 | else: |
| 45 | lst[i - 1], lst[i] = lst[i], lst[i - 1] |
| 46 | i -= 1 |
| 47 | if i == 0: |
| 48 | i = 1 |
| 49 | |
| 50 | return lst |
| 51 | |
| 52 | |
| 53 | if __name__ == "__main__": |