Java Online Compiler
Example: Right Array Rotation using Temporary Array in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Right Array Rotation using Temporary Array import java.util.Arrays; // Main class containing the entry point of the program public class Main { /** * Performs a right rotation on an array by 'd' positions. * * @param arr The array to be rotated. * @param d The number of positions to rotate right. */ static void rightRotate(int[] arr, int d) { // Handle edge cases: null array or empty array if (arr == null || arr.length == 0) { return; } int n = arr.length; // Adjust d to be within array bounds d = d % n; // Step 1: Create a temporary array to store the last d elements int[] temp = new int[d]; for (int i = 0; i < d; i++) { // Copy elements from (n - d) to (n - 1) into temp temp[i] = arr[n - d + i]; } // Step 2: Shift the remaining elements (from 0 to n-d-1) to the right // These elements move to positions (i + d). Loop backwards to avoid overwriting elements // before they are moved. for (int i = n - d - 1; i >= 0; i--) { arr[i + d] = arr[i]; } // Step 3: Copy the elements from the temporary array to the beginning of the original array for (int i = 0; i < d; i++) { arr[i] = temp[i]; } } public static void main(String[] args) { // Example 1 int[] arr1 = {1, 2, 3, 4, 5, 6, 7}; int d1 = 2; // Number of positions to rotate right System.out.println("Original Array: " + Arrays.toString(arr1)); rightRotate(arr1, d1); // Perform right rotation System.out.println("Array after " + d1 + " right rotations: " + Arrays.toString(arr1)); System.out.println("-------------------------------------"); // Example 2 int[] arr2 = {10, 20, 30, 40, 50}; int d2 = 3; System.out.println("Original Array: " + Arrays.toString(arr2)); rightRotate(arr2, d2); System.out.println("Array after " + d2 + " right rotations: " + Arrays.toString(arr2)); } }
Output
Clear
ADVERTISEMENTS