Cyclic Sort for Bounded Values
Place a permutation of 1 through n at its matching positions.
python, cyclic sort, arrays, constraintsA value points to its destination
When a list is a permutation of 1 through n, value v belongs at
position v - 1. Swap a misplaced value into its destination and inspect
the new occupant before moving on.
Python illustration
def cyclic_sort(values):
n = len(values)
if any(type(value) is not int for value in values) or set(values) != set(range(1, n + 1)):
raise ValueError("expected a permutation of 1 through n")
i = 0
while i < n:
target = values[i] - 1
if target == i:
i += 1
else:
values[i], values[target] = values[target], values[i]
return values
print(cyclic_sort([3, 1, 2]))
Prepared output: [1, 2, 3]. The list is changed in place.
See the reasoning
Follow the example one step at a time
Put each value at index value minus one. This is a prepared teaching demonstration, not live code execution.
Place 3
[3, 1, 2] → [2, 1, 3] index 0 3 is at index 2
Swap 3 with the value at its target index 2.
Limits matter
For integer inputs meeting the permutation contract, each swap places at least one value in its final position; completed positions stay correct. Placement takes O(n) time and O(1) extra space. The explicit set-based validation adds O(n) expected time and O(n) space, so the complete function uses O(n) extra space. This is not a general-purpose sort: duplicates, out-of-range values, non-integers and booleans are rejected. The explicit type check matters because Python booleans compare equal to integers.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
