Skip to content

Commit fcc8a28

Browse files
grochedixcclauss
andauthored
Gnome sort : type hints, docstrings, doctests (#2307)
* gnome_sort : type hints, docstring, doctests * !Gadeimnoprstu Co-authored-by: Christian Clauss <[email protected]>
1 parent b3ae392 commit fcc8a28

File tree

1 file changed

+41
-10
lines changed

1 file changed

+41
-10
lines changed

sorts/gnome_sort.py

+41-10
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,56 @@
1-
"""Gnome Sort Algorithm."""
1+
"""
2+
Gnome Sort Algorithm (A.K.A. Stupid Sort)
23
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.
37
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
838

939
i = 1
1040

11-
while i < len(unsorted):
12-
if unsorted[i - 1] <= unsorted[i]:
41+
while i < len(lst):
42+
if lst[i - 1] <= lst[i]:
1343
i += 1
1444
else:
15-
unsorted[i - 1], unsorted[i] = unsorted[i], unsorted[i - 1]
45+
lst[i - 1], lst[i] = lst[i], lst[i - 1]
1646
i -= 1
1747
if i == 0:
1848
i = 1
1949

50+
return lst
51+
2052

2153
if __name__ == "__main__":
2254
user_input = input("Enter numbers separated by a comma:\n").strip()
2355
unsorted = [int(item) for item in user_input.split(",")]
24-
gnome_sort(unsorted)
25-
print(unsorted)
56+
print(gnome_sort(unsorted))

0 commit comments

Comments
 (0)