Rotation algorithm

A rotation algorithm swaps two contiguous ranges of elements (range start to mid with range mid to end) possibly uneven in size and, like sorting algorithms, there are numerous solutions to this problem.

Triple Reversal
The triple reversal is the simplest rotation algorithm. It reverses the first block, then the second, and finally both blocks combined.

The algorithm is in-place and makes $$3|A|+3|B|$$ (or $$O(n)$$) data moves. In practice, it performs relatively well due to its simple logic and predictable access patterns, but it is beaten by algorithms that make fewer data moves such as the block swap algorithm or, its optimized variant, the conjoined triple reversal.

This rotation method is also the most parallelizable as the swaps and reversals do not overlap and can be done concurrently, yielding O(1) depth.

In C-like pseudocode:

void triple_reversal(int start, int mid, int end) { reverse(start, mid); //reverse range start to mid reverse(mid, end); //reverse range mid to end reverse(start, end); //reverse the whole range }

Gries-Mills's Block Swap
Pseudocode implementation: procedure gries_mills(T* array, int left, int right) do if left <= right do blockswap array and array+right of size left if right-left > 0 do gries_mills(array, left, right-left) end if else do blockswap array and array+left of size right if left-right > 0 do gries_mills(array+right, left-right, right) end if end if end

Bentley's Juggling
Bentley's Juggling is a rotation algorithm that uses cycles to rotate items. It also makes $$O(n)$$ moves, however, it is not very cache-friendly, and is therefore beaten by Gries-Mills and Triple Reversal algorithms.

Pseudocode: procedure bentleys_juggling(T* array, int amount, int size) do int steps = gcd(amount, size) for i = 0 up to steps - 1 do elem temp = array[i] int j = i        loop do # Loop until it breaks out of the loop int k = j + amount if k >= size do k -= size end if if k == i do break end if arr[j] = arr[k] j = k        end loop arr[j] = temp end for end