Java Online Compiler
Example: ArrayRotationOneByOne in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// ArrayRotationOneByOne import java.util.Arrays; public class Main { // Function to rotate array by one position to the left static void rotateByOne(int[] arr) { int temp = arr[0]; // Store the first element for (int i = 0; i < arr.length - 1; i++) { arr[i] = arr[i + 1]; // Shift elements to the left } arr[arr.length - 1] = temp; // Place the stored element at the end } // Function to rotate array by d positions public static void rotateArrayOneByOne(int[] arr, int d) { int n = arr.length; d = d % n; // Ensure d is within array bounds for effective rotation for (int i = 0; i < d; i++) { rotateByOne(arr); // Rotate d times } } 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)); rotateArrayOneByOne(arr1, d1); System.out.println("Rotated Array (One by One, d=" + d1 + "): " + Arrays.toString(arr1)); int[] arr2 = {10, 20, 30, 40, 50}; int d2 = 3; System.out.println("\nOriginal Array: " + Arrays.toString(arr2)); rotateArrayOneByOne(arr2, d2); System.out.println("Rotated Array (One by One, d=" + d2 + "): " + Arrays.toString(arr2)); } }
Output
Clear
ADVERTISEMENTS