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
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:
- 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.
- 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.
- 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++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
bool isSorted( int arr[], int n)
{
vector< int > evenArr, oddArr;
for ( int i = 0; i < n; i++) {
if (i % 2 == 0)
evenArr.push_back(arr[i]);
else
oddArr.push_back(arr[i]);
}
sort(evenArr.begin(), evenArr.end());
sort(oddArr.begin(), oddArr.end());
int j = 0, k = 0;
vector< int > 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++;
}
for ( int i = 0; i < n - 1; i++) {
if (res[i] > res[i + 1])
return false ;
}
return true ;
}
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
import java.util.*;
class GFG{
static boolean isSorted( int arr[], int n)
{
Vector<Integer> evenArr = new Vector<Integer>();
Vector<Integer> oddArr = new Vector<Integer>();
for ( int i = 0 ; i < n; i++) {
if (i % 2 == 0 )
evenArr.add(arr[i]);
else
oddArr.add(arr[i]);
}
Collections.sort(evenArr);
Collections.sort(oddArr);
int j = 0 , k = 0 ;
Vector<Integer> res= new Vector<Integer>();;
for ( int i = 0 ; i < n; i++) {
if (i % 2 == 0 ) {
res.add(evenArr.get(j)); j++;
}
else {
res.add(oddArr.get(k)); k++;
}
}
for ( int i = 0 ; i < n - 1 ; i++) {
if (res.get(i) > res.get(i + 1 ))
return false ;
}
return true ;
}
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" );
}
}
}
|
Python3
def isSorted(arr, n):
evenArr = []
oddArr = []
for i in range (n):
if (i % 2 = = 0 ):
evenArr.append(arr[i])
else :
oddArr.append(arr[i])
evenArr.sort()
oddArr.sort()
j = 0
k = 0
res = []
for i in range (n):
if (i % 2 = = 0 ):
res.append(evenArr[j])
j + = 1
else :
res.append(oddArr[k])
k + = 1
for i in range (n - 1 ):
if (res[i] > res[i + 1 ]):
return False
return True
if __name__ = = '__main__' :
arr = [ 4 , 3 , 2 , 5 ]
N = len (arr)
if (isSorted(arr, N)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool isSorted( int [] arr, int n)
{
List< int > evenArr = new List< int >();
List< int > oddArr = new List< int >();
for ( int i = 0; i < n; i++) {
if (i % 2 == 0)
evenArr.Add(arr[i]);
else
oddArr.Add(arr[i]);
}
evenArr.Sort();
oddArr.Sort();
int j = 0, k = 0;
List< int > res = new List< int >();
for ( int i = 0; i < n; i++) {
if (i % 2 == 0) {
res.Add(evenArr[j]);
j++;
}
else {
res.Add(oddArr[k]);
k++;
}
}
for ( int i = 0; i < n - 1; i++) {
if (res[i] > res[i + 1])
return false ;
}
return true ;
}
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" );
}
}
}
|
Javascript
<script>
function isSorted(arr, n) {
let evenArr = [], oddArr = [];
for (let i = 0; i < n; i++) {
if (i % 2 == 0)
evenArr.push(arr[i]);
else
oddArr.push(arr[i]);
}
evenArr.sort( function (a, b) { return a - b });
oddArr.sort( function (a, b) { return a - b });
let j = 0, k = 0;
let res = [];
for (let i = 0; i < n; i++) {
if (i % 2 == 0)
res.push(evenArr[j]), j++;
else
res.push(oddArr[k]), k++;
}
for (let i = 0; i < n - 1; i++) {
if (res[i] > res[i + 1])
return false ;
}
return true ;
}
let arr = [4, 3, 2, 5];
let N = arr.length;
if (isSorted(arr, N)) {
document.write( "Yes" );
}
else {
document.write( "No" );
}
</script>
|
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
Share your thoughts in the comments
Please Login to comment...