Here we will see how to rotate an array to left direction based on the user input shifts.
Sample Input:
Array Size: 5
Shifts Count: 3
Array: 1 2 3 4 5
Output: 4 5 1 2 3
Rotate an Array to Left direction:
Approach:
- Looping the array for ‘n’ times.
- For each time it is getting the first element from the array and stores it into a variable (firstElement).
- Again iterating the array from 0 to length-1 times and replacing the same array values with i+1 (a[i]=a[i+1])
- Finally, add the firstElement to the end of the array (arr[arr.length-1]=firstElement).
Solution:
import java.util.Scanner;
public class ArrayLeftRotation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the Array: ");
int size = scan.nextInt();
System.out.println("Enter the shifts you want to move: ");
int shifts = scan.nextInt();
int[] array = new int[size];
System.out.println("Enter "+size+" elements:");
for (int i=0; i<size; ++i) {
array[i] = scan.nextInt();
}
for (int i=0; i<shifts; ++i) {
rotateArray(array);
}
for (int a : array) {
System.out.print(a+" ");
}
}
public static void rotateArray(int[] arr){
int firstElement = arr[0];
for(int i=0;i<arr.length-1;i++){
arr[i]=arr[i+1];
}
arr[arr.length-1]=firstElement;
}
}
Output:
Enter the size of the Array:
5
Enter the shifts you want to move:
3
Enter 5 elements:
1 2 3 4 5
Output:
4 5 1 2 3
Happy Learning 🙂