Java Online Compiler
Example: CircularArrayRotationTempArray in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CircularArrayRotationTempArray import java.util.Arrays; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int k = 2; // Number of positions to rotate System.out.println("Original Array: " + Arrays.toString(arr)); // Step 1: Handle edge cases for k // If k is greater than array length, reduce it using modulo k = k % arr.length; if (k < 0) { // Handle negative k by converting to equivalent positive rotation k = k + arr.length; } // Step 2: Create a temporary array to store rotated elements int[] temp = new int[arr.length]; // Step 3: Copy elements to the temporary array at their new positions for (int i = 0; i < arr.length; i++) { // Calculate the new index: (current_index + k) % array_length // This ensures elements wrap around temp[(i + k) % arr.length] = arr[i]; } // Step 4: Copy elements back from the temporary array to the original array for (int i = 0; i < arr.length; i++) { arr[i] = temp[i]; } System.out.println("Rotated Array (Temp Array): " + Arrays.toString(arr)); } }
Output
Clear
ADVERTISEMENTS