I am using the below code to rotate a NxN matrix by 90 degrees to the left. But it has some logical error. Most of the elements have rotated, but some haven't still. Please help me correct the code.
int n = 4, x = 1, i, j, temp;
int a[][] = new int[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
a[i][j] = x++;
}
}
for (i = 0; i < n / 2; i++) {
for (j = n - 1; j >= n / 2; j--) {
temp = a[i][j];
a[i][j] = a[n - 1 - i][j];
a[n - 1 - i][j] = a[j][i];
a[j][i] = a[i][n - 1 - j];
a[i][n - 1 - j] = temp;
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("\n");
}