|
1 |
| -"""Gnome Sort Algorithm.""" |
| 1 | +""" |
| 2 | +Gnome Sort Algorithm (A.K.A. Stupid Sort) |
2 | 3 |
|
| 4 | +This algorithm iterates over a list comparing an element with the previous one. |
| 5 | +If order is not respected, it swaps element backward until order is respected with |
| 6 | +previous element. It resumes the initial iteration from element new position. |
3 | 7 |
|
4 |
| -def gnome_sort(unsorted): |
5 |
| - """Pure implementation of the gnome sort algorithm in Python.""" |
6 |
| - if len(unsorted) <= 1: |
7 |
| - return unsorted |
| 8 | +For doctests run following command: |
| 9 | +python3 -m doctest -v gnome_sort.py |
| 10 | +
|
| 11 | +For manual testing run: |
| 12 | +python3 gnome_sort.py |
| 13 | +""" |
| 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 |
8 | 38 |
|
9 | 39 | i = 1
|
10 | 40 |
|
11 |
| - while i < len(unsorted): |
12 |
| - if unsorted[i - 1] <= unsorted[i]: |
| 41 | + while i < len(lst): |
| 42 | + if lst[i - 1] <= lst[i]: |
13 | 43 | i += 1
|
14 | 44 | else:
|
15 |
| - unsorted[i - 1], unsorted[i] = unsorted[i], unsorted[i - 1] |
| 45 | + lst[i - 1], lst[i] = lst[i], lst[i - 1] |
16 | 46 | i -= 1
|
17 | 47 | if i == 0:
|
18 | 48 | i = 1
|
19 | 49 |
|
| 50 | + return lst |
| 51 | + |
20 | 52 |
|
21 | 53 | if __name__ == "__main__":
|
22 | 54 | user_input = input("Enter numbers separated by a comma:\n").strip()
|
23 | 55 | unsorted = [int(item) for item in user_input.split(",")]
|
24 |
| - gnome_sort(unsorted) |
25 |
| - print(unsorted) |
| 56 | + print(gnome_sort(unsorted)) |
0 commit comments