Writing a Java program to rotate an array by d elements.

Writing a Java program to rotate an array by d elements. thumbnail
6K
By Dhiraj 09 May, 2020

For any given array of length n, rotating it by elements d means moving it's first d elements either at the end of the array or moving the last d elements to the beginning of the array.

For example, for a given array [1, 2, 3, 4, 5, 6, 7], rotating it by 3 elements will result as [4, 5, 6, 7, 1, 2, 3]. Similarly, rotating the same array by 2 elements will result in [3, 4, 5, 6, 7, 1, 2].

An efficient approach to achieve this would be shifting each d elements by one index ahead of its actual index and inserting each element at the end of the array. Below is the program to achieve the same in Java.

public class ArrayRotation {

    public static int[] rotateBy(int d, int[] input){
        int inputLength = input.length;
        for (int i = 0; i < d; i++){
            int temp = input[0];
            for(int j = 0; j < inputLength - 1; j++){
                input[j] = input[j + 1];
            }
            input[inputLength - 1] = temp;
        }
        return input;
    }

    public static void main(String[] args){

        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        int[] output = ArrayRotation.rotateBy(3, arr);
        System.out.println(Arrays.toString(output));
    }
}

array-rotation

Explanation

For each d element, first store the 0th index element in a temp variable as after every iteration the 0th index element will be the element to be moved to the last index of the array. Now, loop over to each element of the given array and shift each element ahead by one index. This loop should only run till the n-1 index and at the nth index, the value in the temp variable will be placed.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.