From 20b21e5ec9d4ed28ede8bd67d4b5bc924454d4ac Mon Sep 17 00:00:00 2001 From: mateuszz0000 Date: Fri, 5 Jun 2020 09:13:43 +0200 Subject: [PATCH] Refactor cycle_sort (#2072) * Refactor cycle_sort * Undo changes to keep only doctests --- sorts/cycle_sort.py | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/sorts/cycle_sort.py b/sorts/cycle_sort.py index 4ce6a2a0e..d731ea838 100644 --- a/sorts/cycle_sort.py +++ b/sorts/cycle_sort.py @@ -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 # Pass through the array to find cycles to rotate. @@ -37,16 +55,9 @@ def cycle_sort(array): array[pos], item = item, array[pos] ans += 1 - return ans + return array -# Main Code starts here if __name__ == "__main__": - user_input = input("Enter numbers separated by a comma:\n") - unsorted = [int(item) for item in user_input.split(",")] - n = len(unsorted) - cycle_sort(unsorted) - - print("After sort : ") - for i in range(0, n): - print(unsorted[i], end=" ") + assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] + assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]