TheAlgorithms-Python
86 строк · 2.2 Кб
1"""
2This is a Python implementation of the circle sort algorithm
3
4For doctests run following command:
5python3 -m doctest -v circle_sort.py
6
7For manual testing run:
8python3 circle_sort.py
9"""
10
11
12def circle_sort(collection: list) -> list:13"""A pure Python implementation of circle sort algorithm14
15:param collection: a mutable collection of comparable items in any order
16:return: the same collection in ascending order
17
18Examples:
19>>> circle_sort([0, 5, 3, 2, 2])
20[0, 2, 2, 3, 5]
21>>> circle_sort([])
22[]
23>>> circle_sort([-2, 5, 0, -45])
24[-45, -2, 0, 5]
25>>> collections = ([], [0, 5, 3, 2, 2], [-2, 5, 0, -45])
26>>> all(sorted(collection) == circle_sort(collection) for collection in collections)
27True
28"""
29
30if len(collection) < 2:31return collection32
33def circle_sort_util(collection: list, low: int, high: int) -> bool:34"""35>>> arr = [5,4,3,2,1]
36>>> circle_sort_util(lst, 0, 2)
37True
38>>> arr
39[3, 4, 5, 2, 1]
40"""
41
42swapped = False43
44if low == high:45return swapped46
47left = low48right = high49
50while left < right:51if collection[left] > collection[right]:52collection[left], collection[right] = (53collection[right],54collection[left],55)56swapped = True57
58left += 159right -= 160
61if left == right and collection[left] > collection[right + 1]:62collection[left], collection[right + 1] = (63collection[right + 1],64collection[left],65)66
67swapped = True68
69mid = low + int((high - low) / 2)70left_swap = circle_sort_util(collection, low, mid)71right_swap = circle_sort_util(collection, mid + 1, high)72
73return swapped or left_swap or right_swap74
75is_not_sorted = True76
77while is_not_sorted is True:78is_not_sorted = circle_sort_util(collection, 0, len(collection) - 1)79
80return collection81
82
83if __name__ == "__main__":84user_input = input("Enter numbers separated by a comma:\n").strip()85unsorted = [int(item) for item in user_input.split(",")]86print(circle_sort(unsorted))87