Java Online Compiler
Example: Left Array Rotation using Temporary Array in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Left Array Rotation using Temporary Array import java.util.Arrays; // Required for Arrays.toString() // Main class containing the entry point of the program public class Main { /** * Performs a left rotation on an array by 'd' positions. * * @param arr The array to be rotated. * @param d The number of positions to rotate left. */ static void leftRotate(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 (in case d >= n) // A rotation by n is equivalent to no rotation. d = d % n; // Step 1: 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]; } // Step 2: Shift the remaining elements (from index d to n-1) to the left // These elements move to positions (i - d) for (int i = d; i < n; i++) { arr[i - d] = arr[i]; } // Step 3: Copy the elements from the temporary array to the end of the original array // These elements go into positions (n - d + i) for (int i = 0; i < d; i++) { arr[n - d + 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 left System.out.println("Original Array: " + Arrays.toString(arr1)); leftRotate(arr1, d1); // Perform left rotation System.out.println("Array after " + d1 + " left 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)); leftRotate(arr2, d2); System.out.println("Array after " + d2 + " left rotations: " + Arrays.toString(arr2)); } }
Output
Clear
ADVERTISEMENTS