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

  1. Calculate GCD:

    • Calculate the Greatest Common Divisor (GCD) of the array length n and the number of positions d. This step determines the number of cycles needed to rotate all elements.

  2. Perform Cyclic Rotations:

    • Divide the array into gcd cycles, each starting from a specific index i.

    • For each cycle:

      • Initialize a temporary variable temp to hold the value of the current index i.

      • Initialize the current index j to i.

      • While true:

        • Calculate the new index k by adding the rotation distance d to j.

        • Handle wrap-around if k is greater than or equal to the length of the array n by subtracting n from k.

        • Check if k equals the initial index i. If true, break out of the loop as the cycle has completed.

        • Copy the element at index arr[k] to index arr[j], effectively moving the element to its new position within the rotation cycle.

        • Update the current index j to k 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 index j. This step ensures that the entire cycle is properly rotated.

Code

Last updated