Comment
Author: Admin | 2025-04-27
= currEle; // Update the current element to next element currEle = nextEle; // Move to the next index currIdx = nextIdx; } while (currIdx != i); }}int main(){ vectorint> arr = {1, 2, 3, 4, 5, 6}; int d = 2; rotateArr(arr, d); // Print the rotated vector for (int i = 0; i arr.size(); i++) cout arr[i] " "; return 0;} C // C Program to right rotate the array by d positions// using Juggling Algorithm#include #include // Function to rotate arrayvoid rotateArr(int *arr, int n, int d) { // Handle the case where d > size of array d %= n; // Calculate the number of cycles in the rotation int cycles = gcd(n, d); // Process each cycle for (int i = 0; i cycles; i++) { // Start index of current cycle int currIdx = i; int currEle = arr[currIdx]; // Rotate elements till we reach the start of cycle do { int nextIdx = (currIdx + d) % n; int nextEle = arr[nextIdx]; // Update the element at next index with the current element arr[nextIdx] = currEle; // Update the current element to next element currEle = nextEle; // Move to the next index currIdx = nextIdx; } while (currIdx != i); }}// function to compute GCDint gcd(int a, int b) { while (b) { int temp = b; b = a % b; a = temp; } return a;}int main() { int arr[] = {1, 2, 3, 4, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); int d = 2; rotateArr(arr, n, d); // Print the rotated array for (int i = 0; i n; i++) printf("%d ", arr[i]); return 0;} Java // Java Program to right rotate the array by d positions// using Juggling Algorithmimport java.util.Arrays;class GfG { // Function to rotate array static void rotateArr(int[] arr, int d) { int n = arr.length; // Handle the case where d > size of array d %= n; // Calculate the number of cycles in the rotation int cycles = gcd(n, d); // Process each cycle for (int i = 0; i cycles;
Add Comment