MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / cyclic_sort

Function cyclic_sort

sorts/cyclic_sort.py:15–46  ·  view source on GitHub ↗

Sorts the input list of n integers from 1 to n in-place using the Cyclic Sort algorithm. :param nums: List of n integers from 1 to n to be sorted. :return: The same list sorted in ascending order. Time complexity: O(n), where n is the number of integers in the list. Examp

(nums: list[int])

Source from the content-addressed store, hash-verified

13
14
15def 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
49if __name__ == "__main__":

Callers 1

cyclic_sort.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected