C++ Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N

Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation.Â
Note: N is always even.
Examples:Â
Input: A = {1, 2, 3, 4, 5, 6, 7, 8}Â
Output: {7, 4, 1, 6, 3, 8, 5, 2}Â
Explanation:Â
Even element = {2, 4, 6, 8}Â
Odd element = {1, 3, 5, 7}Â
Left rotate of even number = {4, 6, 8, 2}Â
Right rotate of odd number = {7, 1, 3, 5}Â
Combining Both odd and even number alternatively.
Input: A = {1, 2, 3, 4, 5, 6}Â
Output: {5, 4, 1, 6, 3, 2}Â
Â
Approach:
- It is clear that the odd elements are always on even index and even elements are always laying on odd index.
- To do left rotation of even number we choose only odd indices.
- To do right rotation of odd number we choose only even indices.
- Print the updated array.
Below is the implementation of the above approach:
C++
// C++ program to implement // the above approach #include<bits/stdc++.h> using namespace std; Â Â // function to left rotate void left_rotate(int arr[]) { Â Â Â Â int last = arr[1]; Â Â Â Â for (int i = 3; i < 6; i = i + 2)Â Â Â Â Â { Â Â Â Â Â Â Â Â arr[i - 2] = arr[i]; Â Â Â Â } Â Â Â Â arr[6 - 1] = last; } Â Â // function to right rotate void right_rotate(int arr[]) { Â Â Â Â int start = arr[6 - 2]; Â Â Â Â for (int i = 6- 4; i >= 0; i = i - 2)Â Â Â Â Â { Â Â Â Â Â Â Â Â arr[i + 2] = arr[i]; Â Â Â Â } Â Â Â Â arr[0] = start; } Â Â // Function to rotate the array void rotate(int arr[]) { Â Â Â Â left_rotate(arr); Â Â Â Â right_rotate(arr); Â Â Â Â for (int i = 0; i < 6; i++)Â Â Â Â Â { Â Â Â Â Â Â Â Â cout << (arr[i]) << " "; Â Â Â Â } } Â Â // Driver code int main() { Â Â Â Â int arr[] = { 1, 2, 3, 4, 5, 6 }; Â Â Â Â Â Â rotate(arr); } Â Â // This code is contributed by rock_cool |
5 4 1 6 3 2
Time Complexity: O(N)Â
Auxiliary Space: O(1)
Â
Please refer complete article on Rotate all odd numbers right and all even numbers left in an Array of 1 to N for more details!



