# Check whether we can sort two arrays by swapping A[i] and B[i]

Given two arrays, we have to check whether we can sort two arrays in strictly ascending order by swapping A[i] and B[i].

Examples:

Input : A[ ]={ 1, 4, 3, 5, 7}, B[ ]={ 2, 2, 5, 8, 9}
Output : True
After swapping A and B, both the arrays are sorted.

Input : A[ ]={ 1, 4, 5, 5, 7}, B[ ]={ 2, 2, 5, 8, 9}
Output : False
It is not possible to make both the arrays sorted with any number of swaps.

We are given two arrays, we can swap A[i] with B[i] so that we can sort both the array in strictly ascending order so we have to sort the array in such a way that A[i] < A[i+1] and B[i] < B[i+1].
We will use a greedy approach and solve the problem.
We will get the minimum and maximum of A[i] and B[i] and assign minimum to B[i] and maximum to A[i].
Now, we will check that array A and array B is strictly increasing or not.
Let us consider our approach is incorrect, (there is possibility to arrange but our approach gives false), that means any one or more position is switched.

That means a[i-1] is not less than a[i] or a[i+1] is not greater than a[i] . Now if a[i] is not greater than a[i-1] we cannot switch a[i] with b[i] as b[i] is always less than a[i]. Now let us take a[i+1] is not greater than a[i] so we can switch a[i] with b[i] as a[i] > b[i], but as a[i] > b[i] and a[i+1]> b[i+1] and a[i]>a[i+1] so a[i] can never be less than b[i+1] so there is no possible switch. We can similarly prove for b[i].

So it is proved that there might be more possible combinations for arranging the array when the output is YES but there is no possible way of arranging the array according to constraints when output is NO.

Below is the implementation of the above approach:

## C++

 `// C++ implementation of above approach` `#include ` `using` `namespace` `std;`   `// Function to check whether both the array can be ` `// sorted in (strictly increasing ) ascending order` `bool` `IsSorted(``int` `A[], ``int` `B[], ``int` `n)` `{` `    ``// Traverse through the array` `    ``// and find out the min and max` `    ``// variable at each position` `    ``// make one array of min variables` `    ``// and another of maximum variable` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``int` `x, y;`   `        ``// Maximum and minimum variable` `        ``x = max(A[i], B[i]);` `        ``y = min(A[i], B[i]);`   `        ``// Assign min value to` `        ``// B[i] and max value to A[i]` `        ``A[i] = x;` `        ``B[i] = y;` `    ``}`   `    ``// Now check whether the array is` `    ``// sorted or not` `    ``for` `(``int` `i = 1; i < n; i++) {` `        ``if` `(A[i] <= A[i - 1] || B[i] <= B[i - 1])` `            ``return` `false``;` `    ``}`   `    ``return` `true``;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `A[] = { 1, 4, 3, 5, 7 };` `    ``int` `B[] = { 2, 2, 5, 8, 9 };` `    ``int` `n = ``sizeof``(A) / ``sizeof``(``int``);`   `    ``cout << (IsSorted(A, B, n) ? ``"True"` `: ``"False"``);`   `    ``return` `0;` `}`

## Java

 `// Java implementation of above approach` `import` `java.io.*;`   `class` `GFG` `{` `        `  `// Function to check whether both the array can be ` `// sorted in (strictly increasing ) ascending order` `static` `boolean` `IsSorted(``int` `[]A, ``int` `[]B, ``int` `n)` `{` `    ``// Traverse through the array` `    ``// and find out the min and max` `    ``// variable at each position` `    ``// make one array of min variables` `    ``// and another of maximum variable` `    ``for` `(``int` `i = ``0``; i < n; i++)` `    ``{` `        ``int` `x, y;`   `        ``// Maximum and minimum variable` `        ``x = Math.max(A[i], B[i]);` `        ``y = Math.min(A[i], B[i]);`   `        ``// Assign min value to` `        ``// B[i] and max value to A[i]` `        ``A[i] = x;` `        ``B[i] = y;` `    ``}`   `    ``// Now check whether the array is` `    ``// sorted or not` `    ``for` `(``int` `i = ``1``; i < n; i++) ` `    ``{` `        ``if` `(A[i] <= A[i - ``1``] || B[i] <= B[i - ``1``])` `            ``return` `false``;` `    ``}`   `    ``return` `true``;` `}`   `// Driver code` `public` `static` `void` `main (String[] args)` `{`   `    ``int` `[]A = { ``1``, ``4``, ``3``, ``5``, ``7` `};` `    ``int` `[]B = { ``2``, ``2``, ``5``, ``8``, ``9` `};` `    ``int` `n = A.length;`   `    ``if``(IsSorted(A, B, n) == ``true``)` `    ``{` `        ``System.out.println(``"True"``);` `    ``}` `    ``else` `    ``{` `        ``System.out.println(``"False"``);` `    ``}` `}` `}`   `// This code is contributed by ajit `

## Python3

 `# Python3 implementation of above approach `   `# Function to check whether both the array can be ` `# sorted in (strictly increasing ) ascending order ` `def` `IsSorted(A, B, n) : `   `    ``# Traverse through the array ` `    ``# and find out the min and max ` `    ``# variable at each position ` `    ``# make one array of min variables ` `    ``# and another of maximum variable ` `    ``for` `i ``in` `range``(n) :` `        `  `        ``# Maximum and minimum variable ` `        ``x ``=` `max``(A[i], B[i]); ` `        ``y ``=` `min``(A[i], B[i]); `   `        ``# Assign min value to ` `        ``# B[i] and max value to A[i] ` `        ``A[i] ``=` `x; ` `        ``B[i] ``=` `y; ` `    `  `    ``# Now check whether the array is ` `    ``# sorted or not ` `    ``for` `i ``in` `range``(``1``, n) :` `        ``if` `(A[i] <``=` `A[i ``-` `1``] ``or` `B[i] <``=` `B[i ``-` `1``]) : ` `            ``return` `False``; `   `    ``return` `True``; `     `# Driver code ` `if` `__name__ ``=``=` `"__main__"` `: ` `    `  `    ``A ``=` `[ ``1``, ``4``, ``3``, ``5``, ``7` `]; ` `    ``B ``=` `[ ``2``, ``2``, ``5``, ``8``, ``9` `]; ` `    `  `    ``n ``=` `len``(A); `   `    ``if` `(IsSorted(A, B, n)) :` `        ``print``(``True``)` `    ``else` `:` `        ``print``(``False``) `   `# This code is contributed by AnkitRai01`

## C#

 `// C# implementation of above approach` `using` `System;`   `class` `GFG` `{` `    `  `// Function to check whether both the array can be ` `// sorted in (strictly increasing ) ascending order` `static` `bool` `IsSorted(``int` `[]A, ``int` `[]B, ``int` `n)` `{` `    ``// Traverse through the array` `    ``// and find out the min and max` `    ``// variable at each position` `    ``// make one array of min variables` `    ``// and another of maximum variable` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``int` `x, y;`   `        ``// Maximum and minimum variable` `        ``x = Math.Max(A[i], B[i]);` `        ``y = Math.Min(A[i], B[i]);`   `        ``// Assign min value to` `        ``// B[i] and max value to A[i]` `        ``A[i] = x;` `        ``B[i] = y;` `    ``}`   `    ``// Now check whether the array is` `    ``// sorted or not` `    ``for` `(``int` `i = 1; i < n; i++) {` `        ``if` `(A[i] <= A[i - 1] || B[i] <= B[i - 1])` `            ``return` `false``;` `    ``}`   `    ``return` `true``;` `}`   `// Driver code` `public` `static` `void` `Main()` `{` `    ``int` `[]A = { 1, 4, 3, 5, 7 };` `    ``int` `[]B = { 2, 2, 5, 8, 9 };` `    ``int` `n = A.Length;`   `    ``if``(IsSorted(A, B, n) == ``true``)` `    ``{` `        ``Console.Write(``"True"``);` `    ``}` `    ``else` `    ``{` `        ``Console.Write(``"False"``);` `    ``}` `}` `}`   `// This code is contributed` `// by Akanksha Rai`

## Javascript

 ``

Output

```True

```

Time Complexity: O(N)
Space Complexity: O(1) as no extra space has been used.

Approach(Brute force approach): Try all possible swaps of elements between the two arrays and check if the resulting arrays are sorted

1. The approach to solve this problem is to iterate over the arrays and check if swapping A[i] and B[i] at the same index results in sorted arrays.
2. f A[i] and B[i] are already sorted, continue. If swapping A[i] and B[i] results in sorted arrays, continue.
3.  If none of the swaps result in sorted arrays, return false. If all swaps result in sorted arrays,
4.  return true.

## C++

 `#include ` `using` `namespace` `std;`   `// Function to check if two arrays can be sorted by swapping elements` `bool` `canSortBySwapping(``int` `A[], ``int` `B[], ``int` `n)` `{` `    ``// Iterate over the array` `    ``for` `(``int` `i = 1; i < n; i++) {` `        ``// If A[i] and B[i] are already sorted, continue` `        ``if` `(A[i] > A[i - 1] && B[i] > B[i - 1]) {` `            ``continue``;` `        ``}`   `        ``// If swapping A[i] and B[i] results in sorted arrays, continue` `        ``if` `(A[i] > B[i - 1] && B[i] > A[i - 1]) {` `            ``continue``;` `        ``}`   `        ``// If swapping A[i] and B[i] does not result in sorted arrays, return false` `        ``return` `false``;` `    ``}`   `    ``// If all swaps result in sorted arrays, return true` `    ``return` `true``;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `A[] = { 1, 4, 3, 5, 7 };` `    ``int` `B[] = { 2, 2, 5, 8, 9 };` `    ``int` `n = ``sizeof``(A) / ``sizeof``(``int``);`   `    ``if` `(canSortBySwapping(A, B, n)) {` `        ``cout << ``"True"` `<< endl;` `    ``} ``else` `{` `        ``cout << ``"False"` `<< endl;` `    ``}`   `    ``return` `0;` `}`

## Java

 `import` `java.util.Arrays;`   `public` `class` `GFG {`   `    ``// Function to check if two arrays can be sorted by swapping elements` `    ``public` `static` `boolean` `canSortBySwapping(``int``[] A, ``int``[] B, ``int` `n) {` `        ``// Iterate over the array` `        ``for` `(``int` `i = ``1``; i < n; i++) {` `            ``// If A[i] and B[i] are already sorted, continue` `            ``if` `(A[i] > A[i - ``1``] && B[i] > B[i - ``1``]) {` `                ``continue``;` `            ``}`   `            ``// If swapping A[i] and B[i] results in sorted arrays, continue` `            ``if` `(A[i] > B[i - ``1``] && B[i] > A[i - ``1``]) {` `                ``continue``;` `            ``}`   `            ``// If swapping A[i] and B[i] does not result in sorted arrays, return false` `            ``return` `false``;` `        ``}`   `        ``// If all swaps result in sorted arrays, return true` `        ``return` `true``;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args) {` `        ``int``[] A = { ``1``, ``4``, ``3``, ``5``, ``7` `};` `        ``int``[] B = { ``2``, ``2``, ``5``, ``8``, ``9` `};` `        ``int` `n = A.length;`   `        ``if` `(canSortBySwapping(A, B, n)) {` `            ``System.out.println(``"True"``);` `        ``} ``else` `{` `            ``System.out.println(``"False"``);` `        ``}` `    ``}` `}`

## Python3

 `# Function to check if two arrays can be sorted by swapping elements` `def` `canSortBySwapping(A, B, n):` `  ``# Iterate over the array` `    ``for` `i ``in` `range``(``1``, n):` `       ``#If A[i] and B[i] are already sorted, continue` `        ``if` `A[i] > A[i ``-` `1``] ``and` `B[i] > B[i ``-` `1``]:` `            ``continue` `       ``# If swapping A[i] and B[i] results in sorted arrays, continue     ` `        ``if` `A[i] > B[i ``-` `1``] ``and` `B[i] > A[i ``-` `1``]:` `            ``continue` `       ``#If swapping A[i] and B[i] does not result in sorted arrays, return false` `        ``return` `False` `    ``#If all swaps result in sorted arrays, return true` `    ``return` `True`   `A ``=` `[``1``, ``4``, ``3``, ``5``, ``7``]` `B ``=` `[``2``, ``2``, ``5``, ``8``, ``9``]` `n ``=` `len``(A)` `if` `canSortBySwapping(A, B, n):` `    ``print``(``"True"``)` `else``:` `    ``print``(``"False"``)`

## C#

 `using` `System;`   `class` `GFG` `{` `    ``// Function to check if two arrays can be sorted by swapping elements` `    ``static` `bool` `CanSortBySwapping(``int``[] A, ``int``[] B, ``int` `n)` `    ``{` `        ``// Iterate over the arrays` `        ``for` `(``int` `i = 1; i < n; i++)` `        ``{` `            ``// If A[i] and B[i] are already sorted, continue` `            ``if` `(A[i] > A[i - 1] && B[i] > B[i - 1])` `            ``{` `                ``continue``;` `            ``}`   `            ``// If swapping A[i] and B[i] results in sorted arrays, continue` `            ``if` `(A[i] > B[i - 1] && B[i] > A[i - 1])` `            ``{` `                ``continue``;` `            ``}`   `            ``// If swapping A[i] and B[i] does not result in sorted arrays, return false` `            ``return` `false``;` `        ``}`   `        ``// If all swaps result in sorted arrays, return true` `        ``return` `true``;` `    ``}`   `    ``static` `void` `Main()` `    ``{` `        ``int``[] A = { 1, 4, 3, 5, 7 };` `        ``int``[] B = { 2, 2, 5, 8, 9 };` `        ``int` `n = A.Length;`   `        ``if` `(CanSortBySwapping(A, B, n))` `        ``{` `            ``Console.WriteLine(``"True"``);` `        ``}` `        ``else` `        ``{` `            ``Console.WriteLine(``"False"``);` `        ``}` `    ``}` `}`

## Javascript

 `// Function to check if two arrays can be sorted by swapping elements` `function` `canSortBySwapping(A, B, n) {` `// Iterate over the array` `  ``for` `(let i = 1; i < n; i++) {` `  ``// If A[i] and B[i] are already sorted, continue` `    ``if` `(A[i] > A[i - 1] && B[i] > B[i - 1]) {` `      ``continue``;` `    ``}` `    ``// If swapping A[i] and B[i] results in sorted arrays, continue` `    ``if` `(A[i] > B[i - 1] && B[i] > A[i - 1]) {` `      ``continue``;` `    ``}` `    ``// If swapping A[i] and B[i] does not result in sorted arrays, ` `    ``// return false` `    ``return` `false``;` `  ``}` `   ``// If all swaps result in sorted arrays, return true` `  ``return` `true``;` `}`   `const A = [1, 4, 3, 5, 7];` `const B = [2, 2, 5, 8, 9];` `const n = A.length;` `if` `(canSortBySwapping(A, B, n)) {` `  ``console.log(``"True"``);` `} ``else` `{` `  ``console.log(``"False"``);` `}`

Output

```True

```

Time Complexity:  O(n), where n is the size of the arrays. This is because the code iterates over the arrays only once
Space Complexity: O(1), which is constant as the code uses only a few variables to keep track of the maximum and minimum values. Therefore, the space used does not depend on the size of the input.

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!