Miscellaneous
Juggling algorithm for array rotation
The Juggling Algorithm is an efficient method for rotating an array of elements to the left or right by a given number of positions. It is particularly useful when you need to rotate an array in-place without using extra space. The algorithm achieves this by moving elements of the array in cycles, where each cycle involves moving one set of elements to their correct positions.
Steps of the Juggling Algorithm with Explanation
Calculate GCD:
Calculate the Greatest Common Divisor (GCD) of the array length
n
and the number of positionsd
. This step determines the number of cycles needed to rotate all elements.
Perform Cyclic Rotations:
Divide the array into
gcd
cycles, each starting from a specific indexi
.For each cycle:
Initialize a temporary variable
temp
to hold the value of the current indexi
.Initialize the current index
j
toi
.While true:
Calculate the new index
k
by adding the rotation distanced
toj
.Handle wrap-around if
k
is greater than or equal to the length of the arrayn
by subtractingn
fromk
.Check if
k
equals the initial indexi
. If true, break out of the loop as the cycle has completed.Copy the element at index
arr[k]
to indexarr[j]
, effectively moving the element to its new position within the rotation cycle.Update the current index
j
tok
to prepare for the next iteration of the loop within the cycle.
After completing the cycle, assign the value of
temp
(initial element of the cycle) to the last indexj
. This step ensures that the entire cycle is properly rotated.
Code
Last updated
Was this helpful?