Check if an array can be sorted by rearranging odd and even-indexed elements or not
Last Updated :
20 Jan, 2023
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: Yes
Explanation:
Swap(3, 1) –> {1, 5, 3, 2, 6}
Swap(5, 2) –> {1, 2, 3, 5, 6}
Input: arr[] = {3, 1, 5, 2, 6}
Output: No
Naive Approach: The idea is to find the minimum element for the even indexes or odd indexes and swap it from the current element if the index of the current element is even or odd respectively.
- Traverse the array arr[] and perform the following operations:
- If the current index is even, traverse the remaining even indices.
- Find the minimum element present in the even-indexed elements.
- Swap the minimum with the current array element.
- Repeat the above steps for all odd-indexed elements also.
- After completing the above operations, if the array is sorted, then it is possible to sort the array.
- Otherwise, it is not possible to sort the array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isSorted( int arr[], int n)
{
for ( int i = 0; i < n - 1; i++)
{
if (arr[i] > arr[i + 1])
return false ;
}
return true ;
}
bool sortPoss( int arr[], int n)
{
for ( int i = 0; i < n; i++)
{
int idx = -1;
int minVar = arr[i];
int j = i;
while (j < n)
{
if (arr[j] < minVar)
{
minVar = arr[j];
idx = j;
}
j = j + 2;
}
if (idx != -1)
{
swap(arr[i], arr[idx]);
}
}
if (isSorted(arr, n))
return true ;
else
return false ;
}
int main()
{
int arr[] = { 3, 5, 1, 2, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
if (sortPoss(arr, n))
cout << "True" ;
else
cout << "False" ;
return 0;
}
|
Java
class GFG{
public static boolean isSorted( int arr[], int n)
{
for ( int i = 0 ; i < n - 1 ; i++)
{
if (arr[i] > arr[i + 1 ])
return false ;
}
return true ;
}
public static boolean sortPoss( int arr[], int n)
{
for ( int i = 0 ; i < n; i++)
{
int idx = - 1 ;
int minVar = arr[i];
int j = i;
while (j < n)
{
if (arr[j] < minVar)
{
minVar = arr[j];
idx = j;
}
j = j + 2 ;
}
if (idx != - 1 )
{
int t;
t = arr[i];
arr[i] = arr[idx];
arr[idx] = t;
}
}
if (isSorted(arr, n))
return true ;
else
return false ;
}
public static void main(String args[])
{
int arr[] = { 3 , 5 , 1 , 2 , 6 };
int n = arr.length;
if (sortPoss(arr, n))
System.out.println( "True" );
else
System.out.println( "False" );
}
}
|
Python3
def isSorted(arr):
for i in range ( len (arr) - 1 ):
if arr[i]>arr[i + 1 ]:
return False
return True
def sortPoss(arr):
for i in range ( len (arr)):
idx = - 1
minVar = arr[i]
for j in range (i, len (arr), 2 ):
if arr[j]<minVar:
minVar = arr[j]
idx = j
if idx ! = - 1 :
arr[i], arr[idx] = arr[idx], arr[i]
if isSorted(arr):
return True
else :
return False
arr = [ 3 , 5 , 1 , 2 , 6 ]
print (sortPoss(arr))
|
C#
using System;
class GFG{
public static bool isSorted( int [] arr, int n)
{
for ( int i = 0; i < n - 1; i++)
{
if (arr[i] > arr[i + 1])
return false ;
}
return true ;
}
public static bool sortPoss( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
{
int idx = -1;
int minVar = arr[i];
int j = i;
while (j < n)
{
if (arr[j] < minVar)
{
minVar = arr[j];
idx = j;
}
j = j + 2;
}
if (idx != -1)
{
int t;
t = arr[i];
arr[i] = arr[idx];
arr[idx] = t;
}
}
if (isSorted(arr, n))
return true ;
else
return false ;
}
static public void Main()
{
int [] arr = { 3, 5, 1, 2, 6 };
int n = arr.Length;
if (sortPoss(arr, n))
Console.WriteLine( "True" );
else
Console.WriteLine( "False" );
}
}
|
Javascript
<script>
function isSorted(arr , n) {
for (i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1])
return false ;
}
return true ;
}
function sortPoss(arr , n) {
for (i = 0; i < n; i++) {
var idx = -1;
var minVar = arr[i];
var j = i;
while (j < n) {
if (arr[j] < minVar) {
minVar = arr[j];
idx = j;
}
j = j + 2;
}
if (idx != -1) {
var t;
t = arr[i];
arr[i] = arr[idx];
arr[idx] = t;
}
}
if (isSorted(arr, n))
return true ;
else
return false ;
}
var arr = [ 3, 5, 1, 2, 6 ];
var n = arr.length;
if (sortPoss(arr, n))
document.write( "True" );
else
document.write( "False" );
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The idea is to check if utilize the fact that we can arrange all the even indexed and odd indexed elements the way we want to use the swap operations.
- Initialize an array, say dupArr[], to store the contents of the given array.
- Sort the array dupArr[].
- Check if all even-indexed elements in the original array are the same as the even-indexed elements in dupArr[].
- If found to be true, then sorting is possible. Otherwise, sorting is not possible.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
bool isEqual(vector< int >&A,vector< int >&B){
if (A.size() != B.size()) return false ;
for ( int i = 0; i < A.size(); i++){
if (A[i] != B[i]) return false ;
}
return true ;
}
bool sortPoss(vector< int >arr){
vector< int >dupArr(arr.begin(),arr.end());
sort(dupArr.begin(),dupArr.end());
vector< int >evenOrg;
vector< int >evenSort;
for ( int i=0;i<arr.size();i+=2){
evenOrg.push_back(arr[i]);
evenSort.push_back(dupArr[i]);
}
sort(evenOrg.begin(),evenOrg.end());
sort(evenSort.begin(),evenSort.end());
return isEqual(evenOrg,evenSort);
}
int main(){
vector< int >arr = {3, 5, 1, 2, 6};
cout << sortPoss(arr) << endl;
}
|
Java
import java.io.*;
import java.util.*;
import java.util.ArrayList;
class GFG {
public static boolean isEqual(ArrayList<Integer> A,ArrayList<Integer> B){
if (A.size() != B.size()) return false ;
for ( int i = 0 ; i < A.size(); i++){
if (A.get(i) != B.get(i)) return false ;
}
return true ;
}
public static boolean sortPoss( int [] arr){
ArrayList<Integer> dupArr = new ArrayList<Integer>();
for ( int i = 0 ; i < arr.length; i++)
{
dupArr.add(arr[i]);
}
Collections.sort(dupArr);
ArrayList<Integer> evenOrg = new ArrayList<Integer>();
ArrayList<Integer> evenSort = new ArrayList<Integer>();
for ( int i = 0 ; i < arr.length; i += 2 ){
evenOrg.add(arr[i]);
evenSort.add(dupArr.get(i));
}
Collections.sort(evenOrg);
Collections.sort(evenSort);
return isEqual(evenOrg,evenSort);
}
public static void main (String[] args)
{
int [] arr = { 3 , 5 , 1 , 2 , 6 };
System.out.println(sortPoss(arr));
}
}
|
Python3
def sortPoss(arr):
dupArr = list (arr)
dupArr.sort()
evenOrg = []
evenSort = []
for i in range ( 0 , len (arr), 2 ):
evenOrg.append(arr[i])
evenSort.append(dupArr[i])
evenOrg.sort()
evenSort.sort()
return evenOrg = = evenSort
arr = [ 3 , 5 , 1 , 2 , 6 ]
print (sortPoss(arr))
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG {
public static bool isEqual(List< int > A,List< int > B){
if (A.Count != B.Count) return false ;
for ( int i = 0; i < A.Count; i++){
if (A[i] != B[i]) return false ;
}
return true ;
}
public static bool sortPoss( int [] arr){
List< int > dupArr = arr.ToList();
dupArr.Sort();
List< int > evenOrg = new List< int >();
List< int > evenSort = new List< int >();
for ( int i = 0; i < arr.Length; i += 2){
evenOrg.Add(arr[i]);
evenSort.Add(dupArr[i]);
}
evenOrg.Sort();
evenSort.Sort();
return isEqual(evenOrg,evenSort);
}
public static void Main( string [] args)
{
int [] arr = {3, 5, 1, 2, 6};
Console.WriteLine(sortPoss(arr));
}
}
|
Javascript
<script>
function isEqual(A,B){
if (A.length != B.length) return false ;
for (let i = 0; i < A.length; i++){
if (A[i] != B[i]) return false ;
}
return true ;
}
function sortPoss(arr){
let dupArr = arr.slice();
dupArr.sort()
let evenOrg = []
let evenSort = []
for (let i=0;i<arr.length;i+=2){
evenOrg.push(arr[i])
evenSort.push(dupArr[i])
}
evenOrg.sort()
evenSort.sort()
return isEqual(evenOrg,evenSort);
}
let arr = [3, 5, 1, 2, 6]
document.write(sortPoss(arr), "</br>" )
</script>
|
Time Complexity: O(N*log(N))
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...