Java Program for Reversal algorithm for array rotation

JavaObject Oriented ProgrammingProgramming

Following is the Java program to implement Reversal algorithm for array rotation −


 Live Demo

public class Demo{
   static void rotate_left(int my_arr[], int no_of_rotation){
      int n = my_arr.length;
      array_reversal(my_arr, 0, no_of_rotation - 1);
      array_reversal(my_arr, no_of_rotation, n - 1);
      array_reversal(my_arr, 0, n - 1);
   static void array_reversal(int my_arr[], int start, int end){
      int temp;
      while (start < end) {
         temp = my_arr[start];
         my_arr[start] = my_arr[end];
         my_arr[end] = temp;
   public static void main(String[] args){
      int my_arr[] = { 45, 67, 89, 91, 23, 0, 11 };
      rotate_left(my_arr, 4);
      System.out.println("The array after rotating is ");
      for (int i = 0; i < my_arr.length; i++)
      System.out.print(my_arr[i] + " ");


The array after rotating is
23 0 11 45 67 89 91

A class named Demo contains a function named 'rotate_left'. The array, and the amount by which the array needs to be rotated is passed as parameter to the function. The length of the array is also assigned to another variable. Another function named 'array_reversal' is defined that takes the array, the bgeinning index and the last index value.

If the starting index is less than the ending index, a 'temp' variable is defined and the elements are swapped. The starting index is incremented and the ending index is decremented. The main function is used to define an array and call the 'rotate_left' function on this array.

Updated on 07-Jul-2020 08:04:24