I have developed the program to rotate the array in java request you to please check it and let me know if there are any flaws in it or where further it can be improved
package com.dataStructures.Arrays;
// Java program for reversal algorithm of array rotation
//Let the array be arr[] = [1, 2, 3, 4, 5, 6, 7], d =2 and n = 7
// A = [1, 2] and B = [3, 4, 5, 6, 7]
//
// Reverse A, we get ArB = [2, 1, 3, 4, 5, 6, 7]
// Reverse B, we get ArBr = [2, 1, 7, 6, 5, 4, 3]
// Reverse all, we get (ArBr)r = [3, 4, 5, 6, 7, 1, 2]
import java.util.Arrays;
class ArrayRotate {
static void leftRotate(int[] arr, int d) {
if (d == 0)
return;
int n = arr.length;
reveresArray(arr, 0, d - 1);
reveresArray(arr, d, n - 1);
reveresArray(arr, 0, n - 1);
}
static void reveresArray(int[] arr, int start, int end) {
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static void printArray(int[] arr) {
Arrays.stream(arr).mapToObj(item -> item + " ").forEach(System.out::print);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int n = arr.length;
int d = 2;
leftRotate(arr, d); // Rotate array by d
printArray(arr);
}
}