|
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 |
| 6 | +order is respected with previous element. |
| 7 | +It resumes the initial iteration from element new position. |
3 | 8 |
|
4 |
| -def gnome_sort(unsorted): |
5 |
| - """Pure implementation of the gnome sort algorithm in Python.""" |
6 |
| - if len(unsorted) <= 1: |
7 |
| - return unsorted |
| 9 | +For doctests run following command: |
| 10 | +python3 -m doctest -v gnome_sort.py |
| 11 | +
|
| 12 | +For manual testing run: |
| 13 | +python3 gnome_sort.py |
| 14 | +""" |
| 15 | + |
| 16 | + |
| 17 | +def gnome_sort(lst: list) -> list: |
| 18 | + """ |
| 19 | + Pure implementation of the gnome sort algorithm in Python |
| 20 | +
|
| 21 | + Take some mutable ordered collection with heterogeneous |
| 22 | + comparable items inside as argument, |
| 23 | + return the same collection ordered by ascending. |
| 24 | +
|
| 25 | + Examples: |
| 26 | + >>> gnome_sort([0, 5, 3, 2, 2]) |
| 27 | + [0, 2, 2, 3, 5] |
| 28 | +
|
| 29 | + >>> gnome_sort([]) |
| 30 | + [] |
| 31 | +
|
| 32 | + >>> gnome_sort([-2, -5, -45]) |
| 33 | + [-45, -5, -2] |
| 34 | + """ |
| 35 | + if len(lst) <= 1: |
| 36 | + return lst |
8 | 37 |
|
9 | 38 | i = 1
|
10 | 39 |
|
11 |
| - while i < len(unsorted): |
12 |
| - if unsorted[i - 1] <= unsorted[i]: |
| 40 | + while i < len(lst): |
| 41 | + if lst[i - 1] <= lst[i]: |
13 | 42 | i += 1
|
14 | 43 | else:
|
15 |
| - unsorted[i - 1], unsorted[i] = unsorted[i], unsorted[i - 1] |
| 44 | + lst[i - 1], lst[i] = lst[i], lst[i - 1] |
16 | 45 | i -= 1
|
17 | 46 | if i == 0:
|
18 | 47 | i = 1
|
19 | 48 |
|
| 49 | + return lst |
| 50 | + |
20 | 51 |
|
21 | 52 | if __name__ == "__main__":
|
22 | 53 | user_input = input("Enter numbers separated by a comma:\n").strip()
|
23 | 54 | unsorted = [int(item) for item in user_input.split(",")]
|
24 |
| - gnome_sort(unsorted) |
25 |
| - print(unsorted) |
| 55 | + print(gnome_sort(unsorted)) |
0 commit comments