I have tried left rotating an array through a brute force approach. It works for some inputs and for others it gives error. Where am I going wrong?
Working Input: 1 2 3 4 5
with rotation of 2
places
Actual Output: 3 4 5 1 2
Not Working Input: 1 2 3 4
with rotation of 2
places
Expected Output: 3 4 1 2
Actual Output: ArrayIndexOutofBoundsException
Code:
import java.util.*;
public class LeftRotation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
int len = in.nextInt();
System.out.println("Enter the elements");
int[] arr = new int[len];
for(int i=0; i<len;i++)
{
arr[i] = in.nextInt();
}
System.out.println("Enter number of times to rotate");
int k = in.nextInt();
int[] arr1 = new int[k];
for(int i=0;i<=k-1;i++)
{
arr1[i]=arr[i];
}
int[] arr2 = new int[len];
for(int i=k;i<=len-1;i++)
{
if(i+k<=len+1)
{
arr2[i-k]=arr[i];
}
}
for(int i=0;i<=k-1;i++)
{
if(i+k<=len)
{
arr2[i+k+1]=arr1[i];
}
}
for(int i=0;i<=len-1;i++)
{
System.out.println(arr2[i]);
}
}
}
I know this is not an efficient way to solve this problem but I want to get the basic solution to this.