Compare commits

...

5 Commits

Author SHA1 Message Date
Sharan Sukesh
1eeee2d9f6
Merge c1994c06e9 into e3bd7721c8 2024-11-18 10:32:59 +01:00
Christian Clauss
e3bd7721c8
validate_filenames.py Shebang python for Windows (#12371) 2024-11-15 14:59:14 +01:00
Sharan Sukesh
c1994c06e9
Update cyclic_sort.py 2023-10-01 23:43:51 +05:30
pre-commit-ci[bot]
06fcd146bf [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2023-10-01 10:08:19 +00:00
Sharan Sukesh
e9779a2e45
Create cyclic_sort.py 2023-10-01 15:13:33 +05:30
2 changed files with 53 additions and 1 deletions

View File

@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!python
import os
try:

52
sorts/cyclic_sort.py Normal file
View File

@ -0,0 +1,52 @@
"""
This is a pure Python implementation of the Cyclic Sort algorithm.
For doctests run following command:
python -m doctest -v cyclic_sort.py
or
python3 -m doctest -v cyclic_sort.py
For manual testing run:
python cyclic_sort.py
"""
def cyclic_sort(nums: list) -> list:
"""
Sorts the input list in-place using the Cyclic Sort algorithm.
:param nums: List of integers to be sorted.
:return: The same list sorted in ascending order.
Time complexity: O(n), where n is the number of elements in the list.
Examples:
>>> cyclic_sort([3, 5, 2, 1, 4])
[1, 2, 3, 4, 5]
>>> cyclic_sort([])
[]
"""
# Perform cyclic sort
i = 0
while i < len(nums):
# Calculate the correct index for the current element
correct_index = nums[i] - 1
# If the current element is not at its correct position,
# swap it with the element at its correct index
if nums[i] != nums[correct_index]:
nums[i], nums[correct_index] = nums[correct_index], nums[i]
else:
# If the current element is already in its correct position,
# move to the next element
i += 1
return nums
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(*cyclic_sort(unsorted), sep=",")