Array rotation 2026-10-31
A right array rotation by sends the entry originally at offset to offset for nonempty length . Equivalently it changes adjacent blocks into when . Identity rotations include and .
Three reversals implement the operation: . Alternatively repeatedly use a block swap to put the smaller block in its final position and recurse on the remaining unresolved segment. Replacing that tail recursion by parameter updates gives constant auxiliary storage. If counts swaps for blocks of lengths , then and for unequal lengths. The Euclidean algorithm shows by induction that , so a right rotation uses element swaps for .
Let and be the lengths of the left and right blocks. Exchange the smaller block with the equally long block at the opposite end.If , split with . The first block swap sends to ; is now in its final suffix. Rotate the remaining prefix of length right by to send to . If , split with . The swap sends to ; the fixed prefix is , and rotating the remaining length- suffix right by restores . In both cases the exchanged segments are disjoint.
PROCEDURE rotate(i, n, k: INTEGER);
VAR a, b: INTEGER;
BEGIN
IF (k = 0) OR (k = n) THEN RETURN END;
a := n-k; b := k;
IF a = b THEN
blockswap(i, i+a, a)
ELSIF a < b THEN
blockswap(i, i+b, a);
rotate(i, b, b-a)
ELSE
blockswap(i, i+a, b);
rotate(i+b, a, b)
END
END rotate;The remaining length strictly decreases, so induction on proves algorithm termination and correctness. This implements the block-exchange rotation. It uses only simple explicit variables, but its recursive call stack can have depth when one block has length ; the iterative version removes that extra storage.