Computer >> Computer tutorials >  >> Programming >> Java

Java Program for array rotation


Following is the Java program for array rotation −

Example

public class Demo{
   void rotate_left(int my_arr[], int d, int len){
      d = d % len;
      int i, j, k, temp;
      int divisor = greatest_Common_divisor(d, len);
      for (i = 0; i < divisor; i++){
         temp = my_arr[i];
         j = i;
         while (true){
            k = j + d;
            if (k >= len)
            k = k - len;
            if (k == i)
            break;
            my_arr[j] = my_arr[k];
            j = k;
         }
         my_arr[j] = temp;
      }
   }
   void display_arr(int my_arr[], int size){
      int i;
      for (i = 0; i < size; i++)
      System.out.print(my_arr[i] + " ");
   }
   int greatest_Common_divisor(int a, int b){
      if (b == 0)
      return a;
      else
      return greatest_Common_divisor(b, a % b);
   }
   public static void main(String[] args){
      Demo my_inst = new Demo();
      int my_arr[] = { 5, 7, 89, 91, 34, 21, 11, 0 };
      System.out.println("Rotating the array to the left ");
      my_inst.rotate_left(my_arr, 2, 8);
      System.out.println("Displaying the array from a specific index ");
      my_inst.display_arr(my_arr, 8);
   }
}

Output

Rotating the array to the left
Displaying the array from a specific index
89 91 34 21 11 0 5 7

A class named Demo contains a static function named ‘rotate_left’. Here, the array is passed as one of the parameters to the function, ‘d’ is the amount by which the array should be rotated and ‘len’ is the size of the array. The ‘greatest_common_divisor’ function is called by passing the value of ‘d’ and ‘len’. A ‘for’ loop is iterated over the result of function call to ‘greatest_common_divisor’.

A function named 'display_arr' is defined that is used to display the array elements. Another function 'greatest_Common_divisor' is defined to find the greatest common divisor among two numbers, it is a recursive function. In the main function, an instance of the class is created. An array is also defined, and the function is called on this object. The relevant data is displayed using the 'display_arr' function.