Open In App

Check if an array can be sorted by swapping adjacent elements such that each element is swapped even number of times

Last Updated : 11 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers, the task is to check if the array can be sorted by swapping adjacent elements any number of times such that each array element is swapped even a number of times.

Examples:

Input: arr[] = {4, 3, 2, 5}
Output: Yes
Explanation:
Below are the possible order of swapping to make the array sorted:

  1. Choose the indices 0 and 1 modifies the array to [3, 4, 2, 5]. Now, the frequency of swapping of {2, 3, 4, 5} is {0, 1, 1, 0} respectively.
  2. Choose the indices 1 and 2 modifies the array to [3, 2, 4, 5]. Now, the frequency of swapping of {2, 3, 4, 5} is {1, 1, 2, 0} respectively.
  3. Choose the indices 0 and 1 modifies the array to [2, 3, 4, 5]. Now, the frequency of swapping of {2, 3, 4, 5} is {2, 2, 2, 0} respectively.

Therefore, every array element is swapped even number of times and the given array is sorted. Hence, print Yes.

Input: arr[] = {1, 2, 3, 5, 4}
Output: No

Approach: The given problem can be solved by observing the fact that two adjacent even or odd indices elements can be swapped as there is no restriction on the number of swapping without changing the middle element. Therefore, the idea is to rearrange the array element at respective even and odd indices and check if the array formed is sorted or not. Follow the steps below to solve the given problem:

  • Store all the array elements arr[i] at the odd indices in another array say odd[].
  • Store all the array elements arr[i] at the even indices in another array say even[].
  • Sort the arrays odd[] and even[] in increasing order.
  • initialize two variables, say j and k as 0 that is used to traverse the arrays odd[] and even[].
  • Iterate over the range [0, N] using the variable i and perform the following steps:
    • If the value of i is odd, then push the element odd[j] in the array res[] and increment the value of j by 1.
    • If the value of i is even, then push the element even[k] in the array res[] and increment the value of j by 1.
  • After completing the above steps, if the array res[] is sorted, then print Yes. Otherwise, print No.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// Function to check if the array can be
// made sorted by adjacent swapping of
// element such that each array element
// is swapped even number of times
bool isSorted(int arr[], int n)
{
    vector<int> evenArr, oddArr;
 
    // Traverse the given array
    for (int i = 0; i < n; i++) {
 
        // Stores all the even positions
        // elements
        if (i % 2 == 0)
            evenArr.push_back(arr[i]);
 
        // Stores all the odd positions
        // elements
        else
            oddArr.push_back(arr[i]);
    }
 
    // Sort the array evenArr[]
    sort(evenArr.begin(), evenArr.end());
 
    // Sort the array oddArr[]
    sort(oddArr.begin(), oddArr.end());
 
    int j = 0, k = 0;
    vector<int> res;
 
    // Combine the elements from evenArr
    // and oddArr in the new array res[]
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0)
            res.push_back(evenArr[j]), j++;
        else
            res.push_back(oddArr[k]), k++;
    }
 
    // Check if the array res[] is
    // sorted or not
    for (int i = 0; i < n - 1; i++) {
        if (res[i] > res[i + 1])
            return false;
    }
 
    // Otherwise, return true
    return true;
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 3, 2, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    if (isSorted(arr, N)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if the array can be
// made sorted by adjacent swapping of
// element such that each array element
// is swapped even number of times
static boolean isSorted(int arr[], int n)
{
    Vector<Integer> evenArr = new Vector<Integer>();
    Vector<Integer> oddArr = new Vector<Integer>();
 
    // Traverse the given array
    for (int i = 0; i < n; i++) {
 
        // Stores all the even positions
        // elements
        if (i % 2 == 0)
            evenArr.add(arr[i]);
 
        // Stores all the odd positions
        // elements
        else
            oddArr.add(arr[i]);
    }
 
    // Sort the array evenArr[]
    Collections.sort(evenArr);
 
    // Sort the array oddArr[]
    Collections.sort(oddArr);
 
    int j = 0, k = 0;
    Vector<Integer> res=new Vector<Integer>();;
 
    // Combine the elements from evenArr
    // and oddArr in the new array res[]
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0) {
            res.add(evenArr.get(j)); j++;
        }
        else {
            res.add(oddArr.get(k)); k++;
        }
    }
 
    // Check if the array res[] is
    // sorted or not
    for (int i = 0; i < n - 1; i++) {
        if (res.get(i) > res.get(i + 1))
            return false;
    }
 
    // Otherwise, return true
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 4, 3, 2, 5 };
    int N = arr.length;
 
    if (isSorted(arr, N)) {
        System.out.print("Yes");
    }
    else {
        System.out.print("No");
    }
 
}
}
 
// This code is contributed by shikhasingrajput


Python3




# Python3 program for the above approach
 
# Function to check if the array can be
# made sorted by adjacent swapping of
# element such that each array element
# is swapped even number of times
def isSorted(arr, n):
     
    evenArr = []
    oddArr = []
 
    # Traverse the given array
    for i in range(n):
         
        # Stores all the even positions
        # elements
        if (i % 2 == 0):
            evenArr.append(arr[i])
 
        # Stores all the odd positions
        # elements
        else:
            oddArr.append(arr[i])
 
    # Sort the array evenArr[]
    evenArr.sort()
 
    # Sort the array oddArr[]
    oddArr.sort()
 
    j = 0
    k = 0
    res = []
 
    # Combine the elements from evenArr
    # and oddArr in the new array res[]
    for i in range(n):
        if (i % 2 == 0):
            res.append(evenArr[j])
            j += 1
        else:
            res.append(oddArr[k])
            k += 1
 
    # Check if the array res[] is
    # sorted or not
    for i in range(n - 1):
        if (res[i] > res[i + 1]):
            return False
 
    # Otherwise, return true
    return True
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 4, 3, 2, 5 ]
    N = len(arr)
 
    if (isSorted(arr, N)):
        print("Yes")
    else:
        print("No")
         
# This code is contributed by SURENDRA_GANGWAR


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
   
    // Function to check if the array can be
    // made sorted by adjacent swapping of
    // element such that each array element
    // is swapped even number of times
    static bool isSorted(int[] arr, int n)
    {
        List<int> evenArr = new List<int>();
        List<int> oddArr = new List<int>();
 
        // Traverse the given array
        for (int i = 0; i < n; i++) {
 
            // Stores all the even positions
            // elements
            if (i % 2 == 0)
                evenArr.Add(arr[i]);
 
            // Stores all the odd positions
            // elements
            else
                oddArr.Add(arr[i]);
        }
 
        // Sort the array evenArr[]
        evenArr.Sort();
 
        // Sort the array oddArr[]
        oddArr.Sort();
 
        int j = 0, k = 0;
        List<int> res = new List<int>();
 
        // Combine the elements from evenArr
        // and oddArr in the new array res[]
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                res.Add(evenArr[j]);
                j++;
            }
            else {
                res.Add(oddArr[k]);
                k++;
            }
        }
 
        // Check if the array res[] is
        // sorted or not
        for (int i = 0; i < n - 1; i++) {
            if (res[i] > res[i + 1])
                return false;
        }
 
        // Otherwise, return true
        return true;
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 4, 3, 2, 5 };
        int N = arr.Length;
 
        if (isSorted(arr, N)) {
            Console.Write("Yes");
        }
        else {
            Console.Write("No");
        }
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
 
        // JavaScript program for the above approach;
 
 
        // Function to check if the array can be
        // made sorted by adjacent swapping of
        // element such that each array element
        // is swapped even number of times
        function isSorted(arr, n) {
            let evenArr = [], oddArr = [];
 
            // Traverse the given array
            for (let i = 0; i < n; i++) {
 
                // Stores all the even positions
                // elements
                if (i % 2 == 0)
                    evenArr.push(arr[i]);
 
                // Stores all the odd positions
                // elements
                else
                    oddArr.push(arr[i]);
            }
 
            // Sort the array evenArr[]
            evenArr.sort(function (a, b) { return a - b });
 
            // Sort the array oddArr[]
            oddArr.sort(function (a, b) { return a - b });
 
            let j = 0, k = 0;
            let res = [];
 
            // Combine the elements from evenArr
            // and oddArr in the new array res[]
            for (let i = 0; i < n; i++) {
                if (i % 2 == 0)
                    res.push(evenArr[j]), j++;
                else
                    res.push(oddArr[k]), k++;
            }
 
            // Check if the array res[] is
            // sorted or not
            for (let i = 0; i < n - 1; i++) {
                if (res[i] > res[i + 1])
                    return false;
            }
 
            // Otherwise, return true
            return true;
        }
 
        // Driver Code
 
        let arr = [4, 3, 2, 5];
        let N = arr.length;
 
        if (isSorted(arr, N)) {
            document.write("Yes");
        }
        else {
            document.write("No");
        }
 
 
   // This code is contributed by Potta Lokesh
    </script>


Output: 

Yes

 

Time Complexity: O(N*log N), the inbuilt sort function takes N log N time to complete all operations.
Auxiliary Space: O(N), additional array is used that needs to store all elements in the worst case.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads