11"""
22Gnome Sort Algorithm (A.K.A. Stupid Sort)
33
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.
4+ This algorithm iterates over a list, comparing each element with the previous one.
5+ If the order is not respected, it swaps the element backward until the order is correct.
6+ Then it resumes the iteration from the element's new position.
77
8- For doctests run following command :
9- python3 -m doctest -v gnome_sort.py
8+ For doctests, run:
9+ python3 -m doctest -v gnome_sort.py
1010
11- For manual testing run:
12- python3 gnome_sort.py
11+ For manual testing, run:
12+ python3 gnome_sort.py
1313"""
1414
15+ from typing import List , TypeVar
1516
16- def gnome_sort (lst : list ) -> list :
17+ T = TypeVar ("T" ) # Generic type for sorting any comparable data type
18+
19+
20+ def gnome_sort (lst : List [T ], reverse : bool = False ) -> List [T ]:
1721 """
18- Pure implementation of the gnome sort algorithm in Python
22+ Pure implementation of the gnome sort algorithm in Python.
23+
24+ Args:
25+ lst: A list of comparable items to be sorted.
26+ reverse: If True, sorts in descending order. Defaults to False.
1927
20- Take some mutable ordered collection with heterogeneous comparable items inside as
21- arguments, return the same collection ordered by ascending .
28+ Returns:
29+ A sorted list .
2230
2331 Examples:
2432 >>> gnome_sort([0, 5, 3, 2, 2])
2533 [0, 2, 2, 3, 5]
2634
27- >>> gnome_sort([])
35+ >>> gnome_sort([], reverse=True )
2836 []
2937
3038 >>> gnome_sort([-2, -5, -45])
@@ -33,24 +41,27 @@ def gnome_sort(lst: list) -> list:
3341 >>> "".join(gnome_sort(list(set("Gnomes are stupid!"))))
3442 ' !Gadeimnoprstu'
3543 """
36- if len (lst ) <= 1 :
44+ n = len (lst )
45+ if n <= 1 :
3746 return lst
3847
3948 i = 1
40-
41- while i < len (lst ):
42- if lst [i - 1 ] <= lst [i ]:
49+ while i < n :
50+ if (not reverse and lst [i - 1 ] <= lst [i ]) or (reverse and lst [i - 1 ] >= lst [i ]):
4351 i += 1
4452 else :
4553 lst [i - 1 ], lst [i ] = lst [i ], lst [i - 1 ]
46- i -= 1
47- if i == 0 :
48- i = 1
54+ i = max (1 , i - 1 )
4955
5056 return lst
5157
5258
5359if __name__ == "__main__" :
54- user_input = input ("Enter numbers separated by a comma:\n " ).strip ()
55- unsorted = [int (item ) for item in user_input .split ("," )]
56- print (gnome_sort (unsorted ))
60+ try :
61+ user_input = input ("Enter numbers separated by commas:\n " ).strip ()
62+ unsorted = [float (x ) for x in user_input .split ("," ) if x .strip ()]
63+ order = input ("Sort in descending order? (y/n): " ).strip ().lower () == "y"
64+
65+ print ("\n Sorted result:" , gnome_sort (unsorted , reverse = order ))
66+ except ValueError :
67+ print ("❌ Invalid input! Please enter numeric values separated by commas." )
0 commit comments