I wrote a code to rotate an array of size n by d elements. I used temp array to solve the problem. But I am getting different output.There is syntax error in my code. Can anyone help me? Code:
public static void rotate(int a[], int d, int n) {
int temp[] = new int[n];
for (int i = d; i < a.length; i++) {
for (int j = 0; j < n - 2; j++) {
temp[j] = a[i];
}
}
for (int i = 0; i < d; i++) {
for (int j = n - 2; j < temp.length; j++) {
temp[j] = a[i];
}
}
System.out.println("result is");
for (int k = 0; k < temp.length; k++) {
System.out.println(temp[k]);
}
}
public static void main(String[] args) {
int size, d;
Scanner sc = new Scanner(System.in);
System.out.println("enter size");
size = sc.nextInt();
System.out.println("enter rotate count");
d = sc.nextInt();
int a[] = new int[size];
for (int i = 0; i < size; i++) {
a[i] = sc.nextInt();
}
rotate(a, d, size);
}
Input:
enter size 7
enter rotate count 2
input array a[]=1 2 3 4 5 6 7
Output I got:
7 7 7 7 7 2 2
Expected output:
3 4 5 6 7 1 2