Skip to content

Commit 20b21e5

Browse files
authored
Refactor cycle_sort (TheAlgorithms#2072)
* Refactor cycle_sort * Undo changes to keep only doctests
1 parent 7a14285 commit 20b21e5

File tree

1 file changed

+23
-12
lines changed

1 file changed

+23
-12
lines changed

sorts/cycle_sort.py

+23-12
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,23 @@
1-
# Code contributed by Honey Sharma
2-
def cycle_sort(array):
1+
"""
2+
Code contributed by Honey Sharma
3+
Source: https://en.wikipedia.org/wiki/Cycle_sort
4+
"""
5+
6+
7+
def cycle_sort(array: list) -> list:
8+
"""
9+
>>> cycle_sort([4, 3, 2, 1])
10+
[1, 2, 3, 4]
11+
12+
>>> cycle_sort([-4, 20, 0, -50, 100, -1])
13+
[-50, -4, -1, 0, 20, 100]
14+
15+
>>> cycle_sort([-.1, -.2, 1.3, -.8])
16+
[-0.8, -0.2, -0.1, 1.3]
17+
18+
>>> cycle_sort([])
19+
[]
20+
"""
321
ans = 0
422

523
# Pass through the array to find cycles to rotate.
@@ -37,16 +55,9 @@ def cycle_sort(array):
3755
array[pos], item = item, array[pos]
3856
ans += 1
3957

40-
return ans
58+
return array
4159

4260

43-
# Main Code starts here
4461
if __name__ == "__main__":
45-
user_input = input("Enter numbers separated by a comma:\n")
46-
unsorted = [int(item) for item in user_input.split(",")]
47-
n = len(unsorted)
48-
cycle_sort(unsorted)
49-
50-
print("After sort : ")
51-
for i in range(0, n):
52-
print(unsorted[i], end=" ")
62+
assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
63+
assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]

0 commit comments

Comments
 (0)