I am a beginner in programming. To rotate the array to left, I have written the below code. Please point out how to optimize the code and anything I am doing which is not good programming practice.
package arrays;
import java.util.Scanner;
public class ArrayLeftRotation {
public static int[] LeftRotation(int numberOfLeftRotations, int[] a, int[] b) {
int n1 = numberOfLeftRotations, n2 = numberOfLeftRotations;
/*
* First for loop Given array a0=1,a1=2,a3=4,a4=5,a5=6,a6=7; First we
* are shifting the first 3 elements to last 3 slots and the array looks
* like below a0=1,a1=2,a2=3,a3=,a4=1,a5=2,a6=3; The above step we are
* performing through below logic
* a[array.length-numberOfLeftRotations]=b[i]; GIVEN ARRAY LENGTH -
* NUMBER OF LEFT ROTATIONS IS THE STARTING POINT TO MOVE THE FIRST
* ELEMENTS OF THE ARRAY TO LAST
*/
for (int i = 0; i < numberOfLeftRotations; i++) {
a[a.length - n1] = b[i];
n1--;
}
/*
* Second for loop After executing the above loop the array look like
* below a0=1,a1=2,a2=3,a3=,a4=1,a5=2,a6=3; now except the last three
* slots every thing needs to be changed
* a0=4,a1=5,a2=6,a3=7,a4=1,a5=2,a6=3; we achieved the above array
* result through below logic a[i]=b[numberOfLeftRotations]; REPLACED
* THE REMAINING SLOTS WITH THE VALUES STARTING FROM
* NUMBEROFLEFTROTATIONS
*/
for (int i = 0; i < a.length - numberOfLeftRotations; i++) {
a[i] = b[n2];
n2++;
}
return a;
}
public static int[] LeftRotation(int numberOfLeftRotations, int[] a) {
return a;
}
public static int[] printArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
return a;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of Left Rotations need to be done");
int l = sc.nextInt();
System.out.println("Enter number of elements in an array");
int e = sc.nextInt();
int[] a = new int[e];
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
int[] b = a.clone();
LeftRotation(l, a, b);
printArray(a);
}
}