mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-24 05:21:09 +00:00
Refactor cycle_sort (#2072)
* Refactor cycle_sort * Undo changes to keep only doctests
This commit is contained in:
parent
7a14285cb6
commit
20b21e5ec9
|
@ -1,5 +1,23 @@
|
||||||
# Code contributed by Honey Sharma
|
"""
|
||||||
def cycle_sort(array):
|
Code contributed by Honey Sharma
|
||||||
|
Source: https://en.wikipedia.org/wiki/Cycle_sort
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def cycle_sort(array: list) -> list:
|
||||||
|
"""
|
||||||
|
>>> cycle_sort([4, 3, 2, 1])
|
||||||
|
[1, 2, 3, 4]
|
||||||
|
|
||||||
|
>>> cycle_sort([-4, 20, 0, -50, 100, -1])
|
||||||
|
[-50, -4, -1, 0, 20, 100]
|
||||||
|
|
||||||
|
>>> cycle_sort([-.1, -.2, 1.3, -.8])
|
||||||
|
[-0.8, -0.2, -0.1, 1.3]
|
||||||
|
|
||||||
|
>>> cycle_sort([])
|
||||||
|
[]
|
||||||
|
"""
|
||||||
ans = 0
|
ans = 0
|
||||||
|
|
||||||
# Pass through the array to find cycles to rotate.
|
# Pass through the array to find cycles to rotate.
|
||||||
|
@ -37,16 +55,9 @@ def cycle_sort(array):
|
||||||
array[pos], item = item, array[pos]
|
array[pos], item = item, array[pos]
|
||||||
ans += 1
|
ans += 1
|
||||||
|
|
||||||
return ans
|
return array
|
||||||
|
|
||||||
|
|
||||||
# Main Code starts here
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
user_input = input("Enter numbers separated by a comma:\n")
|
assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
|
||||||
unsorted = [int(item) for item in user_input.split(",")]
|
assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
|
||||||
n = len(unsorted)
|
|
||||||
cycle_sort(unsorted)
|
|
||||||
|
|
||||||
print("After sort : ")
|
|
||||||
for i in range(0, n):
|
|
||||||
print(unsorted[i], end=" ")
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user