Refactor cycle_sort (#2072)

* Refactor cycle_sort

* Undo changes to keep only doctests
This commit is contained in:
mateuszz0000 2020-06-05 09:13:43 +02:00 committed by GitHub
parent 7a14285cb6
commit 20b21e5ec9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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=" ")