Java Online Compiler
Example: CircularArrayRotationOneByOne in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CircularArrayRotationOneByOne import java.util.Arrays; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int k = 2; // Number of positions to rotate System.out.println("Original Array: " + Arrays.toString(arr)); // Step 1: Handle edge cases for k k = k % arr.length; if (k < 0) { k = k + arr.length; } // Step 2: Perform k rotations for (int i = 0; i < k; i++) { int lastElement = arr[arr.length - 1]; // Store the last element // Shift all elements from right to left by one position for (int j = arr.length - 1; j > 0; j--) { arr[j] = arr[j - 1]; } arr[0] = lastElement; // Place the stored last element at the beginning } System.out.println("Rotated Array (One by One): " + Arrays.toString(arr)); } }
Output
Clear
ADVERTISEMENTS