2020-08-14 20:00:08 +00:00
|
|
|
"""
|
|
|
|
Gnome Sort Algorithm (A.K.A. Stupid Sort)
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2020-08-14 20:00:08 +00:00
|
|
|
This algorithm iterates over a list comparing an element with the previous one.
|
|
|
|
If order is not respected, it swaps element backward until order is respected with
|
|
|
|
previous element. It resumes the initial iteration from element new position.
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2020-08-14 20:00:08 +00:00
|
|
|
For doctests run following command:
|
|
|
|
python3 -m doctest -v gnome_sort.py
|
|
|
|
|
|
|
|
For manual testing run:
|
|
|
|
python3 gnome_sort.py
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def gnome_sort(lst: list) -> list:
|
|
|
|
"""
|
|
|
|
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_sort([])
|
|
|
|
[]
|
|
|
|
|
|
|
|
>>> gnome_sort([-2, -5, -45])
|
|
|
|
[-45, -5, -2]
|
|
|
|
|
|
|
|
>>> "".join(gnome_sort(list(set("Gnomes are stupid!"))))
|
|
|
|
' !Gadeimnoprstu'
|
|
|
|
"""
|
|
|
|
if len(lst) <= 1:
|
|
|
|
return lst
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2016-12-04 15:00:20 +00:00
|
|
|
i = 1
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2020-08-14 20:00:08 +00:00
|
|
|
while i < len(lst):
|
|
|
|
if lst[i - 1] <= lst[i]:
|
2016-12-04 15:00:20 +00:00
|
|
|
i += 1
|
|
|
|
else:
|
2020-08-14 20:00:08 +00:00
|
|
|
lst[i - 1], lst[i] = lst[i], lst[i - 1]
|
2016-12-04 15:00:20 +00:00
|
|
|
i -= 1
|
2019-10-05 05:14:13 +00:00
|
|
|
if i == 0:
|
2016-12-04 15:00:20 +00:00
|
|
|
i = 1
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2020-08-14 20:00:08 +00:00
|
|
|
return lst
|
|
|
|
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
|
|
|
unsorted = [int(item) for item in user_input.split(",")]
|
2020-08-14 20:00:08 +00:00
|
|
|
print(gnome_sort(unsorted))
|