|
| 1 | +""" |
| 2 | +This is a pure Python implementation of the Cyclic Sort algorithm. |
| 3 | +
|
| 4 | +For doctests run following command: |
| 5 | +python -m doctest -v cyclic_sort.py |
| 6 | +or |
| 7 | +python3 -m doctest -v cyclic_sort.py |
| 8 | +For manual testing run: |
| 9 | +python cyclic_sort.py |
| 10 | +""" |
| 11 | + |
| 12 | +def cyclic_sort(nums: list) -> list: |
| 13 | + """ |
| 14 | + Sorts the input list in-place using the Cyclic Sort algorithm. |
| 15 | +
|
| 16 | + :param nums: List of integers to be sorted. |
| 17 | + :return: The same list sorted in ascending order. |
| 18 | +
|
| 19 | + Time complexity: O(n), where n is the number of elements in the list. |
| 20 | +
|
| 21 | + Examples: |
| 22 | + >>> cyclic_sort([3, 5, 2, 1, 4]) |
| 23 | + [1, 2, 3, 4, 5] |
| 24 | + >>> cyclic_sort([]) |
| 25 | + [] |
| 26 | + >>> cyclic_sort([-2, -5, -45]) |
| 27 | + [-45, -5, -2] |
| 28 | + """ |
| 29 | + |
| 30 | + # Perform cyclic sort |
| 31 | + i = 0 |
| 32 | + while i < len(nums): |
| 33 | + # Calculate the correct index for the current element |
| 34 | + correct_index = nums[i] - 1 |
| 35 | + |
| 36 | + # If the current element is not at its correct position, |
| 37 | + # swap it with the element at its correct index |
| 38 | + if nums[i] != nums[correct_index]: |
| 39 | + nums[i], nums[correct_index] = nums[correct_index], nums[i] |
| 40 | + else: |
| 41 | + # If the current element is already in its correct position, |
| 42 | + # move to the next element |
| 43 | + i += 1 |
| 44 | + |
| 45 | + return nums |
| 46 | + |
| 47 | +if __name__ == "__main__": |
| 48 | + import doctest |
| 49 | + |
| 50 | + doctest.testmod() |
| 51 | + user_input = input("Enter numbers separated by a comma:\n").strip() |
| 52 | + unsorted = [int(item) for item in user_input.split(",")] |
| 53 | + print(*cyclic_sort(unsorted), sep=",") |
0 commit comments