VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cycle-sort/

⇱ Cycle Sort - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Cycle Sort

Last Updated : 14 Apr, 2026

Cycle Sort is an in-place, unstable, comparison-based sorting algorithm that is optimal in terms of the minimum number of memory writes.

  • The idea is to divide the array into cycles, where each cycle consists of elements that belong to each other’s correct positions, and then rotate these cycles to place all elements correctly.
  • In Cycle Sort, each element is written at most once to its correct position, making it useful in situations where write operations are costly.

Example:

Input: arr[] = [2, 4, 5, 1, 3]
Output: [1,2,3,4,5]
Explanation:

  • 2 -> correct index 1
  • 4 -> correct index 3
  • 5 -> correct index 4
  • 1 -> correct index 0
  • 3 -> correct index 2

These form cycles: Cycle 1: 2 -> 4 -> 1 -> 2 , Cycle 2: 5 -> 3 -> 5. After rotating these cycles, array becomes: [1, 2, 3, 4, 5]

Cycle Sort Approach - O(n^2) Time O(1) Space

The main idea is simple:
For every element, count how many elements are smaller than it.
This count gives its correct position in the sorted array.
If the element is not already at its correct position, place it there.
While placing, another element gets displaced -repeat the same process for that element.
This continues until we come back to the starting point, forming a cycle.


Output
1 2 3 4 5 

Cycle Sort for Range [1…N] or [0…N] - O(n) Time O(1) Space

This method is a special optimized version of Cycle Sort that works only when array elements are in the range 1 to N or 0 to N. In this case, we do not need to explicitly detect cycles; instead, we directly place elements at their correct indices using swapping.

If elements are in range 1 to N, then: Correct index of an element = value - 1
Example: 1 -> index 0, 2 -> index 1, …, N -> index N-1

If elements are in range 0 to N, then: Correct index of an element = value itself


Output
1 2 3 4 5 

Advantage of Cycle Sort

  • Auxiliary Space is O(1)
  •  in-place sorting algorithm.
  •  A minimum number of writes to the memory
  •  Cycle sort is useful when the array is stored in EEPROM or FLASH. 
  • The idea of Cycle Sort is used in problems like Minimum Missing Positive and Min Swaps to Sort

Disadvantage  of Cycle Sort

  • Time complexity is O(n²) for general case
  • Not stable
  • Not suitable for large datasets
Comment
Article Tags:
Article Tags: