DEV Community

Cover image for Rotate Array in clock Wise
Rahul Raj
Rahul Raj

Posted on

Rotate Array in clock Wise

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)

What is Clockwise Rotation?

Clockwise rotation means shifting the array elements to the right.
In this process, the last element moves to the first position, and all other elements shift one position to the right.

  • Step for clock wise rotation

Step 1: Reverse whole array

Step 2: Reverse first k elements (0 to k-1)

Step 3: Reverse elements from k to (size-1)


class Main {
public static void reverseArray(int [] arr , int sIndex , int eIndex){
    while(sIndex<eIndex){
        arr[sIndex ]=(arr[sIndex ]+arr[eIndex ])-(arr[eIndex ]=arr[sIndex ]);
        sIndex++; eIndex--;
    }


    }
    public static void main(String[] args) {
        int [] num = {10,20,30,40,50};
        int k =2;
        k = k%num.length;
         System.out.println("original Array : ");
        for(int i = 0 ; i<num.length;i++){
            System.out.print(num[i]+" ");
        }
        // step 1 
        reverseArray(num , 0 , num.length-1);
        //step 2 
        reverseArray(num , 0 , k-1);
        // step 3 
        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]+" ");
        }

    }
}

Enter fullscreen mode Exit fullscreen mode

Output :

original Array : 
1 2 3 4 5 
After 2th clock wise rotation : 
4 5 1 2 3 
Enter fullscreen mode Exit fullscreen mode

Image

Image

Image

Image

Top comments (0)