Skip to content

Refactor cycle_sort #2072

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 5, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions sorts/cycle_sort.py
Original file line number Diff line number Diff line change
@@ -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([])
[]
"""
Comment on lines +8 to +20
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we please break this into two PRs? The first PR should add the tests (lines 8 thru 20) and once that lands, the second PR could refactor the code.

ans = 0

# Pass through the array to find cycles to rotate.
Expand Down Expand Up @@ -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]