Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:

  1. It is clear that the odd elements are always on even index and even elements are always laying on odd index.
  2. To do left rotation of even number we choose only odd indices.
  3. To do right rotation of odd number we choose only even indices.
  4. Print the updated array.

Below is the implementation of the above approach:

Javascript




<script>
  
    // Javascript program to implement
    // the above approach
      
    // function to left rotate
    function left_rotate(arr)
    {
        let last = arr[1];
        for (let i = 3; i < 6; i = i + 2) 
        {
            arr[i - 2] = arr[i];
        }
        arr[6 - 1] = last;
    }
  
    // function to right rotate
    function right_rotate(arr)
    {
        let start = arr[6 - 2];
        for (let i = 6- 4; i >= 0; i = i - 2) 
        {
            arr[i + 2] = arr[i];
        }
        arr[0] = start;
    }
  
    // Function to rotate the array
    function rotate(arr)
    {
        left_rotate(arr);
        right_rotate(arr);
        for (let i = 0; i < 6; i++) 
        {
            document.write(arr[i] + " ");
        }
    }
  
      let arr = [ 1, 2, 3, 4, 5, 6 ];
    
    rotate(arr);
      
</script>

Output:

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!


My Personal Notes arrow_drop_up
Last Updated : 27 Jan, 2022
Like Article
Save Article
Similar Reads
Related Tutorials