Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Create cyclic_sort.py (TheAlgorithms#9256)
* Create cyclic_sort.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update cyclic_sort.py

* updating DIRECTORY.md

* Update cyclic_sort.py

* Update cyclic_sort.py

* Update cyclic_sort.py

* Update cyclic_sort.py

* Update cyclic_sort.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
Co-authored-by: MaximSmolskiy <MaximSmolskiy@users.noreply.github.com>
  • Loading branch information
4 people authored Aug 26, 2025
commit 44cf167175cf2a53080006dbedd40b5f5343ef18
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -1267,6 +1267,7 @@
* [Comb Sort](sorts/comb_sort.py)
* [Counting Sort](sorts/counting_sort.py)
* [Cycle Sort](sorts/cycle_sort.py)
* [Cyclic Sort](sorts/cyclic_sort.py)
* [Double Sort](sorts/double_sort.py)
* [Dutch National Flag Sort](sorts/dutch_national_flag_sort.py)
* [Exchange Sort](sorts/exchange_sort.py)
Expand Down
55 changes: 55 additions & 0 deletions sorts/cyclic_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""
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
or
python3 cyclic_sort.py
"""


def cyclic_sort(nums: list[int]) -> list[int]:
"""
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.

Examples:
>>> cyclic_sort([])
[]
>>> cyclic_sort([3, 5, 2, 1, 4])
[1, 2, 3, 4, 5]
"""

# Perform cyclic sort
index = 0
while index < len(nums):
# Calculate the correct index for the current element
correct_index = nums[index] - 1
# If the current element is not at its correct position,
# swap it with the element at its correct index
if index != correct_index:
nums[index], nums[correct_index] = nums[correct_index], nums[index]
else:
# If the current element is already in its correct position,
# move to the next element
index += 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=",")