Java Online Compiler
Example: ArrayRotationJugglingAlgorithm in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// ArrayRotationJugglingAlgorithm import java.util.Arrays; public class Main { // Function to compute the greatest common divisor (GCD) using Euclidean algorithm static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } // Function to rotate array by d positions using Juggling Algorithm public static void rotateArrayJuggling(int[] arr, int d) { int n = arr.length; d = d % n; // Ensure d is within array bounds if (d == 0 || n == 0 || n == d) { // No rotation needed for d=0, empty array, or full rotation return; } int numCycles = gcd(n, d); // Number of sets/cycles // Iterate through each cycle for (int i = 0; i < numCycles; i++) { // Pick the first element of current cycle and store it in 'temp' int temp = arr[i]; int j = i; // 'j' is the current position // Move elements within this cycle while (true) { int k = (j + d) % n; // Calculate the next position if (k == i) { // If we have completed the cycle break; } arr[j] = arr[k]; // Move element from 'k' to 'j' j = k; // Update 'j' to 'k' } arr[j] = temp; // Place the stored 'temp' element at its final position } } public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4, 5, 6, 7}; int d1 = 2; System.out.println("Original Array: " + Arrays.toString(arr1)); rotateArrayJuggling(arr1, d1); System.out.println("Rotated Array (Juggling, d=" + d1 + "): " + Arrays.toString(arr1)); int[] arr2 = {10, 20, 30, 40, 50}; int d2 = 3; System.out.println("\nOriginal Array: " + Arrays.toString(arr2)); rotateArrayJuggling(arr2, d2); System.out.println("Rotated Array (Juggling, d=" + d2 + "): " + Arrays.toString(arr2)); int[] arr3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int d3 = 3; // n=12, d=3, gcd(12,3)=3. This means 3 cycles. System.out.println("\nOriginal Array: " + Arrays.toString(arr3)); rotateArrayJuggling(arr3, d3); System.out.println("Rotated Array (Juggling, d=" + d3 + "): " + Arrays.toString(arr3)); } }
Output
Clear
ADVERTISEMENTS