Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if Array can be sorted by swapping adjacent elements having odd sum
Next article icon

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

Last Updated : 28 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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


Next Article
Check if Array can be sorted by swapping adjacent elements having odd sum
author
kamabokogonpachiro
Improve
Article Tags :
  • Bit Magic
  • Sorting
  • Geeks Premier League
  • DSA
  • Arrays
  • Geeks-Premier-League-2022
  • Swap-Program
Practice Tags :
  • Arrays
  • Bit Magic
  • Sorting

Similar Reads

  • Check if Array can be sorted by swapping adjacent elements having odd sum
    Given an array arr[], the task is to check if the array can be sorted using the given operation any number of times. In one operation, you can swap any two adjacent elements if their sum is odd. Examples: Input: arr[] = [1, 6, 31, 14]Output: YesExplanation: Swap 31 and 14 (31 + 14 = 45 which is odd)
    7 min read
  • Check if an array of pairs can be sorted by swapping pairs with different first elements
    Given an array arr[] consisting of N pairs, where each pair represents the value and ID respectively, the task is to check if it is possible to sort the array by the first element by swapping only pairs having different IDs. If it is possible to sort, then print "Yes". Otherwise, print "No". Example
    11 min read
  • Shuffle the position of each Array element by swapping adjacent elements
    Given an array arr[], the task is to rearrange the array elements by swapping adjacent elements such that no element remains at the same position after swapping. Examples: Input: arr[] = { 1, 2, 3, 4, 5 } Output: 2 1 5 3 4 Explanation: Adjacent elements are swapped as follows: (1, 2 -> 2, 1) (3,
    10 min read
  • Check if it is possible to sort the array without swapping adjacent elements
    Given an array arr[] of size N, check if it is possible to sort arr[] without swapping adjacent elements. In other words, check if it is possible to sort arr[] by swapping elements but swapping two consecutive element is not allowed. Examples: Input: N = 4, arr[] = {2, 3, 1, 4}Output: YESExplanation
    5 min read
  • Check if the array can be sorted only if the elements on given positions can be swapped
    Given an array arr[] of length N and another array P[] containing {a1, a2, ... ak} which represents the positions of the given array arr[], the task is to check if the array can be sorted by only swapping the elements' arr[ai], arr[ai+1] where 'i' is some element in the array P[].Examples: Input: ar
    8 min read
  • Check if an Array can be Sorted by picking only the corner Array elements
    Given an array arr[] consisting of N elements, the task is to check if the given array can be sorted by picking only corner elements i.e., elements either from left or right side of the array can be chosen. Examples: Input: arr[] = {2, 3, 4, 10, 4, 3, 1} Output: Yes Explanation: The order of picking
    5 min read
  • Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array
    Given an array arr[] of size N, the task is to check if an array can be sorted by swapping only the elements whose GCD (greatest common divisor) is equal to the smallest element of the array. Print “Yes” if it is possible to sort the array. Otherwise, print “No”. Examples: Input: arr[] = {4, 3, 6, 6
    11 min read
  • Check if an array can be sorted by rearranging odd and even-indexed elements or not
    Given an array arr[] of size N, the task is to check if it is possible to sort the array using the following operations: Swap(arr[i], arr[j]), if i & 1 = 1 and j & 1 = 1.Swap(arr[i], arr[j]), if i & 1 = 0 and j & 1 = 0. Examples: Input: arr[] = {3, 5, 1, 2, 6}Output: YesExplanation:
    11 min read
  • Check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array
    Given an array A[] of size N and a binary array B[] of size N, the task is to check if the array A[] can be converted into a sorted array by swapping pairs (A[i], A[j]) if B[i] is not equal to B[j]. If the array A[] can be sorted, then print "Yes". Otherwise, print "No". Examples: Input: A[] = {3, 1
    15 min read
  • Check if all the elements can be made of same parity by inverting adjacent elements
    Given a binary matrix. In a single operation, you are allowed to choose two adjacent elements and invert their parity. The operation can be performed any number of times. Write a program to check if all the elements of the array can be converted into a single parity. Examples: Input: a[] = {1, 0, 1,
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences