Java Online Compiler
Example: ArrayRotationTemporaryArray in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// ArrayRotationTemporaryArray import java.util.Arrays; public class Main { // Function to rotate array by d positions using a temporary array public static void rotateArrayTemp(int[] arr, int d) { int n = arr.length; d = d % n; // Ensure d is within array bounds if (d == 0 || n == 0) { // No rotation needed for d=0 or empty array return; } // Create a temporary array to store the first 'd' elements int[] temp = new int[d]; for (int i = 0; i < d; i++) { temp[i] = arr[i]; } // Shift the remaining (n-d) elements to the beginning for (int i = d; i < n; i++) { arr[i - d] = arr[i]; } // Copy the elements from temp array to the end of the original array for (int i = 0; i < d; i++) { arr[n - d + i] = temp[i]; } } 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)); rotateArrayTemp(arr1, d1); System.out.println("Rotated Array (Temp Array, d=" + d1 + "): " + Arrays.toString(arr1)); int[] arr2 = {10, 20, 30, 40, 50}; int d2 = 3; System.out.println("\nOriginal Array: " + Arrays.toString(arr2)); rotateArrayTemp(arr2, d2); System.out.println("Rotated Array (Temp Array, d=" + d2 + "): " + Arrays.toString(arr2)); } }
Output
Clear
ADVERTISEMENTS