forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircle_sort.py
More file actions
Latest commit
86 lines (64 loc) · 2.22 KB
/
Copy pathcircle_sort.py
File metadata and controls
86 lines (64 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""
This is a Python implementation of the circle sort algorithm
For doctests run following command:
python3 -m doctest -v circle_sort.py
For manual testing run:
python3 circle_sort.py
"""
defcircle_sort(collection: list) ->list:
"""A pure Python implementation of circle sort algorithm
:param collection: a mutable collection of comparable items in any order
:return: the same collection in ascending order
Examples:
>>> circle_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> circle_sort([])
[]
>>> circle_sort([-2, 5, 0, -45])
[-45, -2, 0, 5]
>>> collections = ([], [0, 5, 3, 2, 2], [-2, 5, 0, -45])
>>> all(sorted(collection) == circle_sort(collection) for collection in collections)
True
"""
iflen(collection) <2:
returncollection
defcircle_sort_util(collection: list, low: int, high: int) ->bool:
"""
>>> arr = [5,4,3,2,1]
>>> circle_sort_util(lst, 0, 2)
True
>>> arr
[3, 4, 5, 2, 1]
"""
swapped=False
iflow==high:
returnswapped
left=low
right=high
whileleft<right:
ifcollection[left] >collection[right]:
collection[left], collection[right] = (
collection[right],
collection[left],
)
swapped=True
left+=1
right-=1
ifleft==rightandcollection[left] >collection[right+1]:
collection[left], collection[right+1] = (
collection[right+1],
collection[left],
)
swapped=True
mid=low+int((high-low) /2)
left_swap=circle_sort_util(collection, low, mid)
right_swap=circle_sort_util(collection, mid+1, high)
returnswappedorleft_swaporright_swap
is_not_sorted=True
whileis_not_sortedisTrue:
is_not_sorted=circle_sort_util(collection, 0, len(collection) -1)
returncollection
if__name__=="__main__":
user_input=input("Enter numbers separated by a comma:\n").strip()
unsorted= [int(item) foriteminuser_input.split(",")]
print(circle_sort(unsorted))