Check if array can be sorted with one swap
Last Updated :
13 Apr, 2023
Given an array containing N elements. Find if it is possible to sort it in non-decreasing order using atmost one swap.
Examples:
Input : arr[] = {1, 2, 3, 4}
Output : YES
The array is already sorted
Input : arr[] = {3, 2, 1}
Output : YES
Swap 3 and 1 to get [1, 2, 3]
Input : arr[] = {4, 1, 2, 3}
Output :NO
A simple approach is to sort the array and compare the required position of the element and the current position of the element. If there are no mismatches, the array is already sorted. If there are exactly 2 mismatches, we can swap the terms that are not in the position to get the sorted array.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkSorted( int n, int arr[])
{
int b[n];
for ( int i = 0; i < n; i++)
b[i] = arr[i];
sort(b, b + n);
int ct = 0;
for ( int i = 0; i < n; i++)
if (arr[i] != b[i])
ct++;
if (ct == 0 || ct == 2)
return true ;
else
return false ;
}
int main()
{
int arr[] = {1, 5, 3, 4, 2};
int n = sizeof (arr) / sizeof (arr[0]);
if (checkSorted(n, arr))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.Arrays;
class GFG
{
static boolean checkSorted( int n, int arr[])
{
int []b = new int [n];
for ( int i = 0 ; i < n; i++)
b[i] = arr[i];
Arrays.sort(b, 0 , n);
int ct = 0 ;
for ( int i = 0 ; i < n; i++)
if (arr[i] != b[i])
ct++;
if (ct == 0 || ct == 2 )
return true ;
else
return false ;
}
public static void main(String[] args)
{
int arr[] = { 1 , 5 , 3 , 4 , 2 };
int n = arr.length;
if (checkSorted(n, arr))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python 3
def checkSorted(n, arr):
b = []
for i in range (n):
b.append(arr[i])
b.sort()
ct = 0
for i in range (n):
if arr[i] ! = b[i]:
ct + = 1
if ct = = 0 or ct = = 2 :
return True
else :
return False
if __name__ = = '__main__' :
arr = [ 1 , 5 , 3 , 4 , 2 ]
n = len (arr)
if checkSorted(n, arr):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static Boolean checkSorted( int n, int []arr)
{
int []b = new int [n];
for ( int i = 0; i < n; i++)
b[i] = arr[i];
Array.Sort(b, 0, n);
int ct = 0;
for ( int i = 0; i < n; i++)
if (arr[i] != b[i])
ct++;
if (ct == 0 || ct == 2)
return true ;
else
return false ;
}
public static void Main(String[] args)
{
int []arr = {1, 5, 3, 4, 2};
int n = arr.Length;
if (checkSorted(n, arr))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function checkSorted(n, arr)
{
var b = Array(n).fill(0);
for ( var i = 0; i < n; i++)
b[i] = arr[i];
b.sort();
var ct = 0;
for ( var i = 0; i < n; i++)
if (arr[i] != b[i])
ct++;
if (ct == 0 || ct == 2)
return true ;
else
return false ;
}
var arr = [ 1, 5, 3, 4, 2 ];
var n = arr.length;
if (checkSorted(n, arr))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n Log n)
Space Complexity: O(n) where n is size of input array arr. This is because array b has been created in checkSorted function.
An efficient solution is to check in linear time. Let us consider different cases that may appear after one swap.
- We swap adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 2, 4, 3, 5}
- We swap non-adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 5, 3, 4, 2}
We traverse the given array. For every element, we check if it is smaller than the previous element. We count such occurrences. If the count of such occurrences is more than 2, then we cannot sort the array with one swap. If the count is one, we can find elements to swap (smaller and its previous).
If the count is two, we can find elements to swap (previous of first smaller and second smaller).
After swapping, we again check if the array becomes sorted or not. We check this to handle cases like {4, 1, 2, 3}
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int checkSorted( int n, int arr[])
{
int first = 0, second = 0;
int count = 0;
for ( int i = 1; i < n; i++) {
if (arr[i] < arr[i - 1]) {
count++;
if (first == 0)
first = i;
else
second = i;
}
}
if (count > 2)
return false ;
if (count == 0)
return true ;
if (count == 2)
swap(arr[first - 1], arr[second]);
else if (count == 1)
swap(arr[first - 1], arr[first]);
for ( int i = 1; i < n; i++)
if (arr[i] < arr[i - 1])
return false ;
return true ;
}
int main()
{
int arr[] = { 1, 4, 3, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
if (checkSorted(n, arr))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static boolean checkSorted( int n, int arr[])
{
int first = 0 , second = 0 ;
int count = 0 ;
for ( int i = 1 ; i < n; i++)
{
if (arr[i] < arr[i - 1 ])
{
count++;
if (first == 0 )
first = i;
else
second = i;
}
}
if (count > 2 )
return false ;
if (count == 0 )
return true ;
if (count == 2 )
swap(arr, first - 1 , second);
else if (count == 1 )
swap(arr, first - 1 , first);
for ( int i = 1 ; i < n; i++)
if (arr[i] < arr[i - 1 ])
return false ;
return true ;
}
static int [] swap( int []arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
public static void main(String[] args)
{
int arr[] = { 1 , 4 , 3 , 2 };
int n = arr.length;
if (checkSorted(n, arr))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python 3
def checkSorted(n, arr):
first, second = 0 , 0
count = 0
for i in range ( 1 , n):
if arr[i] < arr[i - 1 ]:
count + = 1
if first = = 0 :
first = i
else :
second = i
if count > 2 :
return False
if count = = 0 :
return True
if count = = 2 :
(arr[first - 1 ],
arr[second]) = (arr[second],
arr[first - 1 ])
elif count = = 1 :
(arr[first - 1 ],
arr[first]) = (arr[first],
arr[first - 1 ])
for i in range ( 1 , n):
if arr[i] < arr[i - 1 ]:
return False
return True
if __name__ = = '__main__' :
arr = [ 1 , 4 , 3 , 2 ]
n = len (arr)
if checkSorted(n, arr):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool checkSorted( int n, int []arr)
{
int first = 0, second = 0;
int count = 0;
for ( int i = 1; i < n; i++)
{
if (arr[i] < arr[i - 1])
{
count++;
if (first == 0)
first = i;
else
second = i;
}
}
if (count > 2)
return false ;
if (count == 0)
return true ;
if (count == 2)
swap(arr, first - 1, second);
else if (count == 1)
swap(arr, first - 1, first);
for ( int i = 1; i < n; i++)
if (arr[i] < arr[i - 1])
return false ;
return true ;
}
static int [] swap( int []arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
public static void Main(String[] args)
{
int []arr = { 1, 4, 3, 2 };
int n = arr.Length;
if (checkSorted(n, arr))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function checkSorted(n, arr)
{
var first = 0, second = 0;
var count = 0;
for ( var i = 1; i < n; i++) {
if (arr[i] < arr[i - 1]) {
count++;
if (first == 0)
first = i;
else
second = i;
}
}
if (count > 2)
return false ;
if (count == 0)
return true ;
if (count == 2)
[arr[first - 1], arr[second]] = [arr[second], arr[first - 1]];
else if (count == 1)
[arr[first - 1], arr[first]] = [arr[first], arr[first - 1]];
for ( var i = 1; i < n; i++)
if (arr[i] < arr[i - 1])
return false ;
return true ;
}
var arr = [1, 4, 3, 2];
var n = arr.length;
if (checkSorted(n, arr))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n)
Space Complexity: O(1) as no extra space has been used.
Exercise: How to check if an array can be sorted with two swaps?
Share your thoughts in the comments
Please Login to comment...