Cycle Sort

Cycle Sort is a sort designed to make the fewest data moves possible. Cycle Sort's complexity differs depending on the variant, but in general, the complexity comes from the time it takes to find an element's final position in the sorted list. Cycle Sort is also not stable, but there are variants such as Stable Cycle that are.

Algorithm
Cycle Sort starts at the first position $$i=0$$ and finds the final destination of the item at $$i$$. It then swaps $$i$$ with the item's destination then finds the destination of the new item at $$i$$ and repeats. If at any point the destination is $$=i$$, Cycle Sort increments $$i$$ instead of swapping. It repeats these processes until it reaches the end of the list.

Since each element is swapped to its final destination, they are swapped at most once and never moved again therefore Cycle Sort makes $$O(n)$$ moves. The simplest version Cycle Sort is generally implemented in $$O(n^2)$$ comparisons and $$O(1)$$ space. To find an item's destination, Cycle Sort iterates through the list counting the amount of elements less that the item. This requires $$O(n)$$ comparisons for $$O(n)$$ items therefore Cycle Sort is $$O(n^2)$$.

Handling equal items
The method given above, however, only works with distinct elements. In the case of equal elements, this method fails by putting Cycle Sort in a perpetual loop. A simple example of this happening is $$arr = [1, 1, 0]$$. Cycle Sort swaps the first $$1$$ in $$arr[0]$$ with $$arr[1]$$ since that is $$1$$'s final destination. However, the item we swapped with is another $$1$$ which swaps to the same position, so the algorithm gets stuck swapping $$arr[0]$$ with $$arr[1]$$ forever.

The solution is to add a check for items equal to the item being swapped away. If Cycle Sort finds that the item in the final destination is equal, it skips that position by incrementing to the right. This ensures that Cycle Sort always swaps distinct items and therefore never gets stuck in an infinite loop. This step also adds an extra worst case of $$O(n)$$ comparisons per element.

Another solution is to allocate $$O(n)$$ extra space and assign a key to each element making them all distinct which avoids this problem entirely.

Pseudocode
procedure cycle_sort(array arr) do for i from 0 to length(arr)-1 do dest = destination of arr[i] # depending on the type of cycle sort this can be O(1), O(n), etc.      while dest != i do swap i and dest in arr dest = destination of arr[i] end while end for end

Implementation
Implementation of in-place O(n^2) Cycle Sort using optimal writes to array in Java: