Cycle sort

Unlike nearly every other sort, items are never written elsewhere in the array simply to push them out of the way of the action.

[citation needed] To illustrate the idea of cycle sort, consider a list with distinct elements.

To create a working implementation from the above outline, two issues need to be addressed: The following Python implementation[1][circular reference] performs cycle sort on an array, counting the number of writes to that array that were needed to sort it.

When the array contains only duplicates of a relatively small number of items, a constant-time perfect hash function can greatly speed up finding where to put an item1, turning the sort from Θ(n2) time to Θ(n + k) time, where k is the total number of hashes.

The proper place of elements can then be found by a constant-time hashing and cumulative sum table lookup rather than a linear search.

Example of cycle sort sorting a list of random numbers.
Example of cycle sort sorting a list of random numbers.
Displacement cycle for list "bdeac", when shifting the first letter b to its correct position: