In this tutorial, we will write a java program to left rotate the elements of an array by a specified number. For example, if an array is: {3, 5, 7, 9, 11} and we are left rotating it by 1 then the resulting array after left rotating would be: {5, 7, 9, 11, 3}.
The concept is simple, all the elements are shifted to the left by the specified number, in the above example all elements were shifted to the left by 1 position. If this number is 2, then the elements shift to left by two positions and first two elements would be shifted to the end of the array.
Let’s take few example to understand the concept and then we will write a program to implement this:
Array is {2, 4, 6, 8, 10, 12} Left rotate by 2 After first rotation: {4, 6, 8, 10, 12, 2} After second rotation: {6, 8, 10, 12, 2, 4} Output array would be {6, 8, 10, 12, 2, 4} Note that the first elements are shifted to the end of the array. Left rotate the same array by 3 Array is {2, 4, 6, 8, 10, 12} After first rotation: {4, 6, 8, 10, 12, 2} After second rotation: {6, 8, 10, 12, 2, 4} After third rotation: {8, 10, 12, 2, 4, 6} Output array {8, 10, 12, 2, 4, 6}
Program to left rotate the elements of a given array
In the following example, we have an array initialized and we have a number n
that represents the number of times the array needs to be left rotated.
We run a loop from 0 till the number n (specifies the left rotation count) and at each iteration of this loop, we shift the element by one to the left.
Which means, the second element would move to 1st position, third element would move to 2nd position and so on. Before moving the second element to 1st position, we store the 1st element in a different variable firstElement
which we add at the end of the array.
class JavaExample { public static void main(String[] args) { //Initializing the array numbers int [] numbers = new int [] {2, 4, 6, 8, 10, 12}; /* This number specifies how many times the array needs * to be rotated. */ int n = 2; System.out.println("Given array is: "); for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } //Left rotate the array by n times for(int i = 0; i < n; i++){ int j, firstElement; //Storing the first element of the array to move to last firstElement = numbers[0]; for(j = 0; j < numbers.length-1; j++){ //Shifting the element to left by 1 on each iteration of loop numbers[j] = numbers[j+1]; } //Adding the first element at the end of the array numbers[j] = firstElement; } System.out.println(); //Printing output array System.out.println("Array after "+n+" left rotations: "); for(int i = 0; i< numbers.length; i++){ System.out.print(numbers[i] + " "); } } }
Output:
Given array is: 2 4 6 8 10 12 Array after 2 left rotations: 6 8 10 12 2 4
Leave a Reply