|
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 | + """ |
3 | 21 | ans = 0
|
4 | 22 |
|
5 | 23 | # Pass through the array to find cycles to rotate.
|
@@ -37,16 +55,9 @@ def cycle_sort(array):
|
37 | 55 | array[pos], item = item, array[pos]
|
38 | 56 | ans += 1
|
39 | 57 |
|
40 |
| - return ans |
| 58 | + return array |
41 | 59 |
|
42 | 60 |
|
43 |
| -# Main Code starts here |
44 | 61 | 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