TheAlgorithms-Python

Форк
0
/
gnome_sort.py 
56 строк · 1.4 Кб
1
"""
2
Gnome Sort Algorithm (A.K.A. Stupid Sort)
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.
7

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
38

39
    i = 1
40

41
    while i < len(lst):
42
        if lst[i - 1] <= lst[i]:
43
            i += 1
44
        else:
45
            lst[i - 1], lst[i] = lst[i], lst[i - 1]
46
            i -= 1
47
            if i == 0:
48
                i = 1
49

50
    return lst
51

52

53
if __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))
57

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.