Rotate Array in clock Wise
Source: Dev.to
What is Array Rotation?
Array rotation is the process of shifting the elements of an array to new positions by a certain number of times (k).
There are two types of array rotation:
- Clockwise rotation (right rotation / right shift)
- Anti‑clockwise rotation (left rotation / left shift)
Clockwise Rotation
Clockwise rotation means shifting the array elements to the right.
Steps for Clockwise Rotation
- Reverse the whole array.
- Reverse the first k elements (indices 0 to k – 1).
- Reverse the elements from k to size – 1.
class Main {
public static void reverseArray(int[] arr, int sIndex, int eIndex) {
while (sIndex length
System.out.println("original Array : ");
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] + " ");
}
// step 1: reverse whole array
reverseArray(num, 0, num.length - 1);
// step 2: reverse first k elements
reverseArray(num, 0, k - 1);
// step 3: reverse remaining elements
reverseArray(num, k, num.length - 1);
System.out.println();
System.out.println("After " + k + "th clock wise rotation : ");
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] + " ");
}
}
}
Sample Output
original Array :
10 20 30 40 50
After 2th clock wise rotation :
40 50 10 20 30