Skip to content
Related Articles

Related Articles

Check if array can be sorted by swapping adjacent elements of opposite parity

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 28 Feb, 2022

Given an array A of size n, the task is to check if the array can be sorted in increasing order, if the only operation allowed is swapping the adjacent elements if they are of opposite parity. The operation can be done any number of times.

Examples:

Input : n = 4, A = [1, 6, 51, 16]
Output: YES
Explanation: Since 51 is odd and 16 is even, we will just swap them. The array now becomes [1, 6, 16, 51], which is sorted in increasing order.

Input: n = 4, A = [5, 5, 5, 5]
Output: YES
Explanation: The array is already sorted.

 

Approach: It can be observed that If either the order of even elements or the order of odd elements is decreasing, then it would be impossible to sort the array. 

We can assume that we are going to sort the array using bubble sort (as in bubble sort also, adjacent elements are swapped until we get sorted array). In bubble sort, if element A[i]>A[j] (where, i<j), then at any point during the iterations, they are bound to be swapped. But, here we have a constraint, that we cannot swap similar parity elements. So, if any of the same parity elements are in decreasing order, it would be impossible to sort the array. 

Follow the steps below to solve the problem – 

  • Create 2 variables named “odd” and “even” to store the previous odd and even elements respectively.
  • Iterate through the array.
  • At each iteration, check if the element is even or odd and compare with previous even or odd element respectively.
  • If current even/odd element is less than previous even/odd element, return false.
  • If the iteration ends, return true, as it would be possible to sort the array,

Below is the implementation of above approach –

C++




// C++ Code for the Check if array can be
// sorted by swapping adjacent elements
// of opposite parity
#include <bits/stdc++.h>
using namespace std;
 
// function to check if the array can be
// sorted in increasing order by
// swappingadjacent elements of same parity
bool canBeSorted(int n, int A[])
{
    // declaring & initializing odd and
    // even variables, that stores previous
    // odd and even elements respectively
    int odd = -1, even = -1;
 
    // declaring and initializing flag
    // variable to store the answer
    int flag = 1;
 
    // iterating through the array
    for (int i = 0; i < n; i++) {
 
        // if the element is odd
        if (A[i] % 2 == 1) {
            if (A[i] < odd) {
                flag = 0;
                break;
            }
 
            // if it is less than previous
            // odd element, then array can
            // not be sorted
            else {
                // else we update the last
                // odd element
                odd = A[i];
            }
        }
 
        // if the element is even
        else {
            if (A[i] < even) {
                flag = 0;
                break;
            }
 
            // if it is less than previous
            // even element, then array can
            // not be sorted
            even = A[i];
 
            // else we update
            // the last even element
        }
    }
 
    // all even elements are sorted and all
    // odd elements are sorted, hence we
    // return true as it is possible to
    // sort the array
    if (flag) {
        return true;
    }
 
    // not possible to sort the array
    return false;
}
 
// Driver Code
int main()
{
    int n = 4;
    int A[] = { 1, 6, 51, 16 };
    bool answer = canBeSorted(n, A);
 
    if (answer == 1) {
        cout << "YES";
    }
    else {
        cout << "NO";
    }
}


Java




// Java Code for the Check if array can be
// sorted by swapping adjacent elements
// of opposite parity
import java.io.*;
 
class GFG {
 
  // function to check if the array can be
  // sorted in increasing order by
  // swappingadjacent elements of same parity
  static Boolean canBeSorted(int n, int A[])
  {
    // declaring & initializing odd and
    // even variables, that stores previous
    // odd and even elements respectively
    int odd = -1, even = -1;
 
    // declaring and initializing flag
    // variable to store the answer
    int flag = 1;
 
    // iterating through the array
    for (int i = 0; i < n; i++) {
 
      // if the element is odd
      if (A[i] % 2 == 1) {
        if (A[i] < odd) {
          flag = 0;
          break;
        }
 
        // if it is less than previous
        // odd element, then array can
        // not be sorted
        else {
          // else we update the last
          // odd element
          odd = A[i];
        }
      }
 
      // if the element is even
      else {
        if (A[i] < even) {
          flag = 0;
          break;
        }
 
        // if it is less than previous
        // even element, then array can
        // not be sorted
        even = A[i];
 
        // else we update
        // the last even element
      }
    }
 
    // all even elements are sorted and all
    // odd elements are sorted, hence we
    // return true as it is possible to
    // sort the array
    if (flag  == 1) {
      return true;
    }
 
    // not possible to sort the array
    return false;
  }
 
  // Driver Code
  public static void main (String[] args) {   
    int n = 4;
    int A[] = { 1, 6, 51, 16 };
    Boolean answer = canBeSorted(n, A);
 
    if (answer == true) {
      System.out.println("YES");
    }
    else {
      System.out.println("NO");
    }
 
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3




# Python Code for the Check if array can be
# sorted by swapping adjacent elements
# of opposite parity
 
# function to check if the array can be
# sorted in increasing order by
# swappingadjacent elements of same parity
def canBeSorted(n, A):
 
    # declaring & initializing odd and
    # even variables, that stores previous
    # odd and even elements respectively
    odd = -1
    even = -1
 
    # declaring and initializing flag
    # variable to store the answer
    flag = 1
 
    # iterating through the array
    for i in range(0, n):
        # if the element is odd
        if (A[i] % 2 == 1):
            if (A[i] < odd):
                flag = 0
                break
 
            # if it is less than previous
            # odd element, then array can
            # not be sorted
            else:
                # else we update the last
                # odd element
                odd = A[i]
 
        # if the element is even
        else:
            if (A[i] < even):
                flag = 0
                break
 
            # if it is less than previous
            # even element, then array can
            # not be sorted
            even = A[i]
 
            # else we update
            # the last even element
 
    # all even elements are sorted and all
    # odd elements are sorted, hence we
    # return true as it is possible to
    # sort the array
    if (flag):
        return True
 
    # not possible to sort the array
    return False
 
# Driver Code
n = 4
A = [1, 6, 51, 16]
answer = canBeSorted(n, A)
 
if (answer == 1):
    print("YES")
 
else:
    print("NO")
 
# This code is contributed by Palak Gupta


C#




// C# Code for the Check if array can be
// sorted by swapping adjacent elements
// of opposite parity
using System;
class GFG {
 
  // function to check if the array can be
  // sorted in increasing order by
  // swappingadjacent elements of same parity
  static bool canBeSorted(int n, int []A)
  {
 
    // declaring & initializing odd and
    // even variables, that stores previous
    // odd and even elements respectively
    int odd = -1, even = -1;
 
    // declaring and initializing flag
    // variable to store the answer
    int flag = 1;
 
    // iterating through the array
    for (int i = 0; i < n; i++) {
 
      // if the element is odd
      if (A[i] % 2 == 1) {
        if (A[i] < odd) {
          flag = 0;
          break;
        }
 
        // if it is less than previous
        // odd element, then array can
        // not be sorted
        else {
          // else we update the last
          // odd element
          odd = A[i];
        }
      }
 
      // if the element is even
      else {
        if (A[i] < even) {
          flag = 0;
          break;
        }
 
        // if it is less than previous
        // even element, then array can
        // not be sorted
        even = A[i];
 
        // else we update
        // the last even element
      }
    }
 
    // all even elements are sorted and all
    // odd elements are sorted, hence we
    // return true as it is possible to
    // sort the array
    if (flag  == 1) {
      return true;
    }
 
    // not possible to sort the array
    return false;
  }
 
  // Driver Code
  public static void Main () {   
    int n = 4;
    int []A = { 1, 6, 51, 16 };
    bool answer = canBeSorted(n, A);
 
    if (answer == true) {
      Console.WriteLine("YES");
    }
    else {
      Console.WriteLine("NO");
    }
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
        // JavaScript code for the above approach
 
        // function to check if the array can be
        // sorted in increasing order by
        // swappingadjacent elements of same parity
        function canBeSorted(n, A)
        {
         
            // declaring & initializing odd and
            // even variables, that stores previous
            // odd and even elements respectively
            let odd = -1, even = -1;
 
            // declaring and initializing flag
            // variable to store the answer
            let flag = 1;
 
            // iterating through the array
            for (let i = 0; i < n; i++) {
 
                // if the element is odd
                if (A[i] % 2 == 1) {
                    if (A[i] < odd) {
                        flag = 0;
                        break;
                    }
 
                    // if it is less than previous
                    // odd element, then array can
                    // not be sorted
                    else
                    {
                     
                        // else we update the last
                        // odd element
                        odd = A[i];
                    }
                }
 
                // if the element is even
                else {
                    if (A[i] < even) {
                        flag = 0;
                        break;
                    }
 
                    // if it is less than previous
                    // even element, then array can
                    // not be sorted
                    even = A[i];
 
                    // else we update
                    // the last even element
                }
            }
 
            // all even elements are sorted and all
            // odd elements are sorted, hence we
            // return true as it is possible to
            // sort the array
            if (flag) {
                return true;
            }
 
            // not possible to sort the array
            return false;
        }
 
        // Driver Code
        let n = 4;
        let A = [1, 6, 51, 16];
        let answer = canBeSorted(n, A);
 
        if (answer == 1) {
            document.write("YES");
        }
        else {
            document.write("NO");
        }
 
       // This code is contributed by Potta Lokesh
    </script>


Output

YES

Time Complexity: O(n), where n is the size of the array
Auxiliary Space:  O(1), as no extra space is being used


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!