Given an array, A of size N consisting of elements 1 to N. A boolean array B consisting of N-1 elements indicates that if B[i] is 1, then A[i] can be swapped with A[i+1]. Find out if A can be sorted by swapping elements.
Examples:
Input : A[] = {1, 2, 5, 3, 4, 6}
B[] = {0, 1, 1, 1, 0}
Output : A can be sorted
We can swap A[2] with A[3] and then A[3] with A[4].
Input : A[] = {2, 3, 1, 4, 5, 6}
B[] = {0, 1, 1, 1, 1}
Output : A can not be sorted
We can not sort A by swapping elements as 1 can never be swapped with A[0]=2.
Method 1: Here we can swap only A[i] with A[i+1]. So to find whether array can be sorted or not. Using boolean array B we can sort array for a continuous sequence of 1 for B. At last, we can check, if A is sorted or not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool sortedAfterSwap( int A[], bool B[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++) {
if (B[i]) {
j = i;
while (B[j])
j++;
sort(A + i, A + 1 + j);
i = j;
}
}
for (i = 0; i < n; i++) {
if (A[i] != i + 1)
return false ;
}
return true ;
}
int main()
{
int A[] = { 1, 2, 5, 3, 4, 6 };
bool B[] = { 0, 1, 1, 1, 0 };
int n = sizeof (A) / sizeof (A[0]);
if (sortedAfterSwap(A, B, n))
cout << "A can be sorted\n" ;
else
cout << "A can not be sorted\n" ;
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
static boolean sortedAfterSwap( int A[],
boolean B[], int n)
{
int i, j;
for (i = 0 ; i < n - 1 ; i++) {
if (B[i]) {
j = i;
while (B[j]) {
j++;
}
Arrays.sort(A, i, 1 + j);
i = j;
}
}
for (i = 0 ; i < n; i++) {
if (A[i] != i + 1 ) {
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
int A[] = { 1 , 2 , 5 , 3 , 4 , 6 };
boolean B[] = { false , true , true , true , false };
int n = A.length;
if (sortedAfterSwap(A, B, n)) {
System.out.println( "A can be sorted" );
}
else {
System.out.println( "A can not be sorted" );
}
}
}
|
Python3
def sortedAfterSwap(A, B, n) :
for i in range ( 0 , n - 1 ) :
if (B[i] = = 1 ) :
j = i
while (B[j] = = 1 ) :
j = j + 1
A = A[ 0 :i] + sorted (A[i:j + 1 ]) + A[j + 1 :]
i = j
for i in range ( 0 , n) :
if (A[i] ! = i + 1 ) :
return False
return True
A = [ 1 , 2 , 5 , 3 , 4 , 6 ]
B = [ 0 , 1 , 1 , 1 , 0 ]
n = len (A)
if (sortedAfterSwap(A, B, n)) :
print ( "A can be sorted" )
else :
print ( "A can not be sorted" )
|
C#
using System;
class GFG {
static bool sortedAfterSwap( int [] A,
bool [] B,
int n)
{
int i, j;
for (i = 0; i < n - 1; i++) {
if (B[i]) {
j = i;
while (B[j]) {
j++;
}
Array.Sort(A, i, 1 + j);
i = j;
}
}
for (i = 0; i < n; i++) {
if (A[i] != i + 1) {
return false ;
}
}
return true ;
}
public static void Main()
{
int [] A = { 1, 2, 5, 3, 4, 6 };
bool [] B = { false , true , true , true , false };
int n = A.Length;
if (sortedAfterSwap(A, B, n)) {
Console.WriteLine( "A can be sorted" );
}
else {
Console.WriteLine( "A can not be sorted" );
}
}
}
|
Javascript
<script>
function sortedAfterSwap(A, B, n)
{
let i, j;
for (i = 0; i < n - 1; i++) {
if (B[i]) {
j = i;
while (B[j]) {
j++;
}
A.sort();
i = j;
}
}
for (i = 0; i < n; i++) {
if (A[i] != i + 1) {
return false ;
}
}
return true ;
}
let A = [ 1, 2, 5, 3, 4, 6 ];
let B = [ false , true , true , true , false ];
let n = A.length;
if (sortedAfterSwap(A, B, n)) {
document.write( "A can be sorted" );
}
else {
document.write( "A can not be sorted" );
}
</script>
|
PHP
<?php
function sortedAfterSwap( $A , $B , $n )
{
for ( $i = 0; $i < $n - 1; $i ++)
{
if ( $B [ $i ])
{
$j = $i ;
while ( $B [ $j ])
$j ++;
sort( $A );
$i = $j ;
}
}
for ( $i = 0; $i < $n ; $i ++)
{
if ( $A [ $i ] != $i + 1)
return false;
}
return true;
}
$A = array (1, 2, 5, 3, 4, 6);
$B = array (0, 1, 1, 1, 0);
$n = count ( $A );
if (sortedAfterSwap( $A , $B , $n ))
echo "A can be sorted\n" ;
else
echo "A can not be sorted\n" ;
?>
|
Time Complexity: O(n*n*logn), where n time is used for iterating and n*logn for sorting inside the array
Auxiliary Space: O(1), as no extra space is required
Method 2:
Here we discuss a very intuitive approach which too gives the answer in O(n) time for all cases. The idea here is that whenever the binary array has 1, we check if that index in array A has i+1 or not. If it does not contain i+1, we simply swap a[i] with a[i+1].
The reason for this is that the array should have i+1 stored at index i. And if at the array is sortable, then the only operation allowed is swapping. Hence, if the required condition is not satisfied, we simply swap. If the array is sortable, swapping will take us one step closer to the correct answer. And as expected, if the array is not sortable, then swapping would lead to just another unsorted version of the same array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool sortedAfterSwap( int A[], bool B[], int n)
{
for ( int i = 0; i < n - 1; i++) {
if (B[i]) {
if (A[i] != i + 1)
swap(A[i], A[i + 1]);
}
}
for ( int i = 0; i < n; i++) {
if (A[i] != i + 1)
return false ;
}
return true ;
}
int main()
{
int A[] = { 1, 2, 5, 3, 4, 6 };
bool B[] = { 0, 1, 1, 1, 0 };
int n = sizeof (A) / sizeof (A[0]);
if (sortedAfterSwap(A, B, n))
cout << "A can be sorted\n" ;
else
cout << "A can not be sorted\n" ;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int sortedAfterSwap( int [] A,
int [] B, int n)
{
int t = 0 ;
for ( int i = 0 ; i < n - 1 ; i++)
{
if (B[i] != 0 )
{
if (A[i] != i + 1 )
t = A[i];
A[i] = A[i + 1 ];
A[i + 1 ] = t;
}
}
for ( int i = 0 ; i < n; i++)
{
if (A[i] != i + 1 )
return 0 ;
}
return 1 ;
}
public static void main(String[] args)
{
int [] A = { 1 , 2 , 5 , 3 , 4 , 6 };
int [] B = { 0 , 1 , 1 , 1 , 0 };
int n = A.length;
if (sortedAfterSwap(A, B, n) == 0 )
System.out.println( "A can be sorted" );
else
System.out.println( "A can not be sorted" );
}
}
|
Python3
def sortedAfterSwap(A,B,n):
for i in range ( 0 ,n - 1 ):
if B[i]:
if A[i]! = i + 1 :
A[i], A[i + 1 ] = A[i + 1 ], A[i]
for i in range (n):
if A[i]! = i + 1 :
return False
return True
if __name__ = = '__main__' :
A = [ 1 , 2 , 5 , 3 , 4 , 6 ]
B = [ 0 , 1 , 1 , 1 , 0 ]
n = len (A)
if (sortedAfterSwap(A, B, n)) :
print ( "A can be sorted" )
else :
print ( "A can not be sorted" )
|
C#
using System;
class GFG
{
static int sortedAfterSwap( int [] A,
int [] B, int n)
{
int t = 0;
for ( int i = 0; i < n - 1; i++)
{
if (B[i] != 0)
{
if (A[i] != i + 1)
t = A[i];
A[i] = A[i + 1];
A[i + 1] = t;
}
}
for ( int i = 0; i < n; i++)
{
if (A[i] != i + 1)
return 0;
}
return 1;
}
public static void Main()
{
int [] A = { 1, 2, 5, 3, 4, 6 };
int [] B = { 0, 1, 1, 1, 0 };
int n = A.Length;
if (sortedAfterSwap(A, B, n) == 0)
Console.WriteLine( "A can be sorted" );
else
Console.WriteLine( "A can not be sorted" );
}
}
|
Javascript
<script>
function sortedAfterSwap(A,B,n)
{
let t = 0;
for (let i = 0; i < n - 1; i++)
{
if (B[i] != 0)
{
if (A[i] != i + 1)
t = A[i];
A[i] = A[i + 1];
A[i + 1] = t;
}
}
for (let i = 0; i < n; i++)
{
if (A[i] != i + 1)
return 0;
}
return 1;
}
let A = [ 1, 2, 5, 3, 4, 6 ];
let B = [ 0, 1, 1, 1, 0 ];
let n = A.length;
if (sortedAfterSwap(A, B, n) == 0)
document.write( "A can be sorted" );
else
document.write( "A can not be sorted" );
</script>
|
PHP
<?php
function sortedAfterSwap(& $A , & $B , $n )
{
for ( $i = 0; $i < $n - 1; $i ++)
{
if ( $B [ $i ])
{
if ( $A [ $i ] != $i + 1)
{
$t = $A [ $i ];
$A [ $i ] = $A [ $i + 1];
$A [ $i + 1] = $t ;
}
}
}
for ( $i = 0; $i < $n ; $i ++)
{
if ( $A [ $i ] != $i + 1)
return false;
}
return true;
}
$A = array ( 1, 2, 5, 3, 4, 6 );
$B = array ( 0, 1, 1, 1, 0 );
$n = sizeof( $A );
if (sortedAfterSwap( $A , $B , $n ))
echo "A can be sorted\n" ;
else
echo "A can not be sorted\n" ;
?>
|
Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.
Approach#3: Using Sorting
First, we sort the array A. Then, we compare each element of the sorted array A with its corresponding element in the original array. If they are not equal, we increment a counter. If the counter is less than or equal to B.count(1), we can sort the array by swapping adjacent elements.
Algorithm
1. Sort the array A.
2. Initialize a counter c to 0.
3. For each element A[i] in the sorted array A, compare it with the corresponding element in the original array.
4. If they are not equal, increment the counter c.
5. If c is less than or equal to B.count(1), return “A can be sorted”.
6. Otherwise, return “A can not be sorted”.
C++
#include <algorithm>
#include <iostream>
using namespace std;
string canSort( int A[], int B[], int n)
{
int sortedA[n];
copy(A, A + n, sortedA);
sort(sortedA, sortedA + n);
int c = 0;
for ( int i = 0; i < n; i++) {
if (A[i] != sortedA[i]) {
c += 1;
}
}
int count = 0;
for ( int i = 0; i < n; i++) {
if (B[i] == 1) {
count += 1;
}
}
if (c <= count) {
return "A can be sorted" ;
}
else {
return "A can not be sorted" ;
}
}
int main()
{
int A[] = { 1, 2, 5, 3, 4, 6 };
int B[] = { 0, 1, 1, 1, 0 };
int n = sizeof (A) / sizeof (A[0]);
cout << canSort(A, B, n) << endl;
}
|
Java
import java.util.Arrays;
public class CanSort {
public static String canSort( int [] A, int [] B) {
int n = A.length;
int [] sortedA = A.clone();
Arrays.sort(sortedA);
int c = 0 ;
for ( int i = 0 ; i < n; i++) {
if (A[i] != sortedA[i]) {
c += 1 ;
}
}
int count = 0 ;
for ( int b : B) {
if (b == 1 ) {
count += 1 ;
}
}
if (c <= count) {
return "A can be sorted" ;
} else {
return "A can not be sorted" ;
}
}
public static void main(String[] args) {
int [] A = { 1 , 2 , 5 , 3 , 4 , 6 };
int [] B = { 0 , 1 , 1 , 1 , 0 };
System.out.println(canSort(A, B));
}
}
|
Python3
def can_sort(A, B):
n = len (A)
sorted_A = sorted (A)
c = 0
for i in range (n):
if A[i] ! = sorted_A[i]:
c + = 1
if c < = B.count( 1 ):
return "A can be sorted"
else :
return "A can not be sorted"
A = [ 1 , 2 , 5 , 3 , 4 , 6 ]
B = [ 0 , 1 , 1 , 1 , 0 ]
print (can_sort(A, B))
|
C#
using System;
using System.Linq;
public class Program {
public static void Main() {
int [] A = {1, 2, 5, 3, 4, 6};
int [] B = {0, 1, 1, 1, 0};
Console.WriteLine(CanSort(A, B));
}
public static string CanSort( int [] A, int [] B) {
int n = A.Length;
int [] sorted_A = A.OrderBy(x => x).ToArray();
int c = 0;
for ( int i = 0; i < n; i++) {
if (A[i] != sorted_A[i]) {
c++;
}
}
if (c <= B.Count(x => x == 1)) {
return "A can be sorted" ;
}
else {
return "A can not be sorted" ;
}
}
}
|
Javascript
function can_sort(A, B) {
const n = A.length;
const sorted_A = A.slice().sort();
let c = 0;
for (let i = 0; i < n; i++) {
if (A[i] !== sorted_A[i]) {
c += 1;
}
}
if (c <= B.filter((num) => num === 1).length) {
return "A can be sorted" ;
} else {
return "A can not be sorted" ;
}
}
const A = [1, 2, 5, 3, 4, 6];
const B = [0, 1, 1, 1, 0];
console.log(can_sort(A, B));
|
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
01 Aug, 2023
Like Article
Save Article