Skip to content
StackDecode
Array techniquesAnimated

Cyclic Sort

Put each value at the index it belongs to by swapping.

Time

O(n)

Extra space

O(1)

Use it for

Values in range 1..n; finding missing/duplicate numbers.

How it works

  1. If the values are exactly 1..n, value v belongs at index v − 1.
  2. Look at the item at index i. If it is not in its place, swap it into the index it belongs to.
  3. Keep swapping at the same i until the right value arrives, then move on.
  4. Every swap places one item for good, so it is O(n) with no extra memory.

Watch it run

Loading animation…