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:
14 | 52 | 41 | 63 | 74 |
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.
14 | 52 | 41 | 63 | 74 |
0 1 2 3 4
After shifting the array will be:
63 | 74 | 14 | 52 | 41 |
0 1 2 3 4
INPUT: The elements of the array
OUTPUT: Array after rotating it right two times
PROCESS:
Step 1: [Taking the input]
Read n [number of elements]
For i=0 to n-1 repeat
Read a[i]
[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[1]<-t1
Set a[0]<-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.
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.
The space complexity of the program is O(n) where ‘n’ is the number of elements of the array.