Java Program For Array Rotation by rotating one-by-one

  • At each iteration, shift the elements by one position to the left circularly (i.e., first element becomes the last).
  • Perform this operation d times to rotate the elements to the left by d position.

Illustration:

Let us take arr[] = [1, 2, 3, 4, 5, 6, 7]d = 2.

First Step:
        => Rotate to left by one position.
        => arr[] = {2, 3, 4, 5, 6, 7, 1}

Second Step:
        => Rotate again to left by one position
        => arr[] = {3, 4, 5, 6, 7, 1, 2}

Rotation is done by 2 times.
So the array becomes arr[] = {3, 4, 5, 6, 7, 1, 2}

Step-by-step approach:

  • Rotate the array to left by one position. For that do the following:
    • Store the first element of the array in a temporary variable.
    • Shift the rest of the elements in the original array by one place.
    • Update the last index of the array with the temporary variable.
  • Repeat the above steps for the number of left rotations required.

Below is the implementation of the above approach:

Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
     
    public static void rotate(int arr[], int d, int n)
    {
        int p = 1;
        while (p <= d) {
            int last = arr[0];
            for (int i = 0; i < n - 1; i++) {
                arr[i] = arr[i + 1];
            }
            arr[n - 1] = last;
            p++;
        }
 
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
     
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
        int N = arr.length;
        // Rotate 2 times
        int d = 2;
 
        // Function call
        rotate(arr, d, N);
    }
}
// contributed by keerthikarathan123


Output

3 4 5 6 7 1 2 

Time Complexity: O(N * d)
Auxiliary Space: O(1)

Java Program For Array Rotation

Write a Java Program for a given array of integers arr[] of size N and an integer, the task is to rotate the array elements to the left by d positions.

Examples:  

Input: 
arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2
Output: 3 4 5 6 7 1 2

Input: arr[] = {3, 4, 5, 6, 7, 1, 2}, d=2
Output: 5 6 7 1 2 3 4

Similar Reads

Java Program For Array Rotation using temp array:

After rotating d positions to the left, the first d elements become the last d elements of the array First store the elements from index d to N-1 into the temp array. Then store the first d elements of the original array into the temp array. Copy back the elements of the temp array into the original array...

Java Program For Array Rotation by rotating one-by-one:

...

Java Program For Array Rotation using Juggling Algorithm:

At each iteration, shift the elements by one position to the left circularly (i.e., first element becomes the last). Perform this operation d times to rotate the elements to the left by d position....

Contact Us