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