# CREATE OWN LIBRARY

## Right Rotate by 2 of an Array

Back to Programming

### Description

The elements are taken as the input. The array is rotated right twice. That means, the element of index 0 is stored in index 2, the element of index 1 is stored in index 3 and so on. And the element of index n-1 is stored in index 1, the element of index n-2 is stored in index 0.

Let the array be:

0                                    1                                 2                                     3                                 4

First the element of index n-1 (here, 74) and n-2 (here, 63) will be stored in a temporary variable and at last the values will be stored at index 1 and 0 respectively.

0                                    1                                 2                                     3                                 4

After shifting the array will be:

0                                    1                                     2                                    3                                    4

### Algorithm

INPUT: The elements of the array

OUTPUT: Array after rotating it right two times

PROCESS:

Step 1: [Taking the input]

For i=0 to n-1 repeat

[End of ‘for’ loop]

Step 2: [Right Rotating the array]

Set t1<-a[n-1]

Set t2<-a[n-2]

For i=n-1 to 2 decremented by 1 repeat

Set a[i]<-a[i-2]

[End of ‘for’ loop]

Set a<-t1

Set a<-t2

[Printing the array after rotation]

Print "The array after rotation: "

For i=0 to n-1 repeat

Print a[i]

[End of ‘for’ loop]

Step 3: Stop.

## TIME COMPLEXITY:

for(i=n-1;i>1;i--)---------------------------------O(n)

a[i]=a[i-2];

The time complexity of this program is O(n) where ‘n’ is the number of elements of the array.

## SPACE COMPLEXITY:

The space complexity of the program is O(n) where ‘n’ is the number of elements of the array.