Java Online Compiler
Example: Left Array Rotation One-by-One in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Left Array Rotation One-by-One import java.util.Arrays; // Main class containing the entry point of the program public class Main { /** * Performs a single left rotation on the array. * The first element moves to the end, and all others shift left. * * @param arr The array to be rotated. */ static void rotateOneElementLeft(int[] arr) { // Handle edge cases: null array or array with 0 or 1 element if (arr == null || arr.length <= 1) { return; } int first = arr[0]; // Step 1: Store the first element // Step 2: Shift remaining elements to the left by one position for (int i = 0; i < arr.length - 1; i++) { arr[i] = arr[i + 1]; } arr[arr.length - 1] = first; // Step 3: Place the stored first element at the end } /** * Performs 'd' left rotations on an array using the one-by-one method. * * @param arr The array to be rotated. * @param d The number of positions to rotate left. */ static void leftRotateOneByOne(int[] arr, int d) { if (arr == null || arr.length == 0) { return; } // Adjust d d = d % arr.length; for (int i = 0; i < d; i++) { rotateOneElementLeft(arr); // Rotate by one element, d times } } public static void main(String[] args) { // Example 1 int[] arr1 = {1, 2, 3, 4, 5}; int d1 = 2; // Number of positions to rotate left System.out.println("Original Array: " + Arrays.toString(arr1)); leftRotateOneByOne(arr1, d1); System.out.println("Array after " + d1 + " left rotations (one-by-one): " + Arrays.toString(arr1)); System.out.println("-------------------------------------"); // Example 2 int[] arr2 = {100, 200, 300, 400, 500, 600}; int d2 = 4; System.out.println("Original Array: " + Arrays.toString(arr2)); leftRotateOneByOne(arr2, d2); System.out.println("Array after " + d2 + " left rotations (one-by-one): " + Arrays.toString(arr2)); } }
Output
Clear
ADVERTISEMENTS