|
| 1 | +package com.array.rotations; |
| 2 | + |
| 3 | +public class ArrayRotation { |
| 4 | + public static void rotateRight(int[] arr, int n) { |
| 5 | + int len = arr.length; |
| 6 | + if (len == 0 || n % len == 0) { |
| 7 | + return; // No rotation needed |
| 8 | + } |
| 9 | + n = n % len; // To handle n greater than length |
| 10 | + reverse(arr, 0, len - 1); // Reverse the whole array |
| 11 | + reverse(arr, 0, n - 1); // Reverse the first part |
| 12 | + reverse(arr, n, len - 1); // Reverse the second part |
| 13 | + } |
| 14 | + |
| 15 | + // Method to rotate an array to the left by n positions |
| 16 | + public static void rotateLeft(int[] arr, int n) { |
| 17 | + int len = arr.length; |
| 18 | + if (len == 0 || n % len == 0) { |
| 19 | + return; // No rotation needed |
| 20 | + } |
| 21 | + n = n % len; // To handle n greater than length |
| 22 | + reverse(arr, 0, n - 1); // Reverse the first part |
| 23 | + reverse(arr, n, len - 1); // Reverse the second part |
| 24 | + reverse(arr, 0, len - 1); // Reverse the whole array |
| 25 | + } |
| 26 | + |
| 27 | + // Helper method to reverse elements in an array between two indices |
| 28 | + private static void reverse(int[] arr, int start, int end) { |
| 29 | + while (start < end) { |
| 30 | + int temp = arr[start]; |
| 31 | + arr[start] = arr[end]; |
| 32 | + arr[end] = temp; |
| 33 | + start++; |
| 34 | + end--; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // Utility method to print the array |
| 39 | + public static void printArray(int[] arr) { |
| 40 | + for (int num : arr) { |
| 41 | + System.out.print(num + " "); |
| 42 | + } |
| 43 | + System.out.println(); |
| 44 | + } |
| 45 | + |
| 46 | + public static void main(String[] args) { |
| 47 | + int[] arrRight = {1, 2, 3, 4, 5}; |
| 48 | + int[] arrLeft = {1, 2, 3, 4, 5}; |
| 49 | + int n = 2; |
| 50 | + |
| 51 | + System.out.println("Original array:"); |
| 52 | + printArray(arrRight); |
| 53 | + |
| 54 | + rotateRight(arrRight, n); |
| 55 | + System.out.println("Array after right rotation by " + n + " positions:"); |
| 56 | + printArray(arrRight); |
| 57 | + |
| 58 | + rotateLeft(arrLeft, n); |
| 59 | + System.out.println("Array after left rotation by " + n + " positions:"); |
| 60 | + printArray(arrLeft); |
| 61 | + } |
| 62 | +} |
0 commit comments