Sorting Array with Two Swaps
Last Updated :
08 Dec, 2023
Given an array A[] that represents a permutation of the N numbers, the task is to determine if it’s possible to sort the array using two swaps. If it is not possible return false otherwise return true.
Examples:
Input: N = 4, A[] = {4, 3, 2, 1}
Output: True
Explanation: Swap(A[1], A[4]), now A[] = {1, 3, 2, 4}, Swap(A[2], A[3]), now A[] = {1, 2, 3, 4}
Input: N = 4, A[] = {4, 3, 1, 2}
Output: False
Explanation: It’s not possible to sort the array in two swaps.
Approach: To solve the problem follow the below idea:
The approach is to determine whether an array can be sorted using two swaps by counting the number of elements that are not in their correct positions. The key functions are findUnsortedCount, which counts the misplaced elements, and swapOne, which swaps an element to its correct position.
Step-by-step algorithm:
- First, we will create a function called “findUnsortedCount” to count the number of elements that are not, in their positions. Start by initializing a variable called “count” to 0.
- Next you will need to loop through the array and compare each element with its expected value (using a 1-based index). If an element doesn’t match its index you should increment the “count” variable.
- Once the loop is complete simply return the value stored in “count“.
- Another function you can create is called “swapOne“. This function will swap an element with the one at its position. To do this iterate through the array. Whenever you find an element that’s not in its correct position swap it with the element at that correct position.
- Finally lets create a function called “checkSorted” which takes an array as input and follows these steps:
- Call the “function to get the count of elements that’re not in their correct positions. Store this count value in a variable named “count“.
- Check if the value of “count” is equal to either 0 or 3. If either condition is true return true because it means that either the array is already sorted or it can be sorted with one swap.
- If the value of “count” is equal, to 4 it indicates that two swaps are needed to sort the array properly. In this case call the “function twice.
- After performing these swaps call findUnsortedCount again. Check if it now returns 0.If this condition is met, then return true to indicate that the array is sorted.
- Otherwise if none of the conditions mentioned above are satisfied return false as it implies that the array cannot be sorted with one or two swaps.
Below is the implementation of above approach:
C++
#include <iostream>
using namespace std;
void swapOne( int array[], int N)
{
for ( int i = 0; i < N; i++) {
if (array[i] != i + 1) {
int temp = array[i];
array[i] = array[temp - 1];
array[temp - 1] = temp;
break ;
}
}
}
int findUnsortedCount( int array[], int N)
{
int count = 0;
for ( int i = 0; i < N; i++) {
if (array[i] != i + 1) {
count++;
}
}
return count;
}
bool checkSorted( int N, int A[])
{
int count = findUnsortedCount(A, N);
if (count == 0 || count == 3) {
return true ;
}
if (count == 4) {
swapOne(A, N);
swapOne(A, N);
return findUnsortedCount(A, N) == 0;
}
return false ;
}
int main()
{
int N = 4;
int A[] = { 4, 3, 2, 1 };
bool isSorted = checkSorted(N, A);
cout << boolalpha << isSorted << endl;
return 0;
}
|
Java
class Main {
public static void main(String[] args)
{
int N = 4 ;
int [] A = { 4 , 3 , 2 , 1 };
boolean isSorted = checkSorted(N, A);
System.out.println(isSorted);
}
static boolean checkSorted( int N, int A[])
{
int count = findUnsortedCount(A);
if (count == 0 || count == 3 ) {
return true ;
}
if (count == 4 ) {
swapOne(A);
swapOne(A);
return findUnsortedCount(A) == 0 ;
}
return false ;
}
static int findUnsortedCount( int [] array)
{
int count = 0 ;
for ( int i = 0 ; i < array.length; i++) {
if (array[i] != i + 1 ) {
count++;
}
}
return count;
}
static void swapOne( int [] array)
{
for ( int i = 0 ; i < array.length; i++) {
if (array[i] != i + 1 ) {
int temp = array[i];
array[i] = array[temp - 1 ];
array[temp - 1 ] = temp;
break ;
}
}
}
}
|
Python3
def check_sorted(N, A):
count = find_unsorted_count(A)
if count = = 0 or count = = 3 :
return True
if count = = 4 :
swap_one(A)
swap_one(A)
return find_unsorted_count(A) = = 0
return False
def find_unsorted_count(array):
count = 0
for i in range ( len (array)):
if array[i] ! = i + 1 :
count + = 1
return count
def swap_one(array):
for i in range ( len (array)):
if array[i] ! = i + 1 :
temp = array[i]
array[i] = array[temp - 1 ]
array[temp - 1 ] = temp
break
N = 4
A = [ 4 , 3 , 2 , 1 ]
is_sorted = check_sorted(N, A)
print (is_sorted)
|
C#
using System;
class GFG
{
static void SwapOne( int [] array, int N)
{
for ( int i = 0; i < N; i++)
{
if (array[i] != i + 1)
{
int temp = array[i];
array[i] = array[temp - 1];
array[temp - 1] = temp;
break ;
}
}
}
static int FindUnsortedCount( int [] array, int N)
{
int count = 0;
for ( int i = 0; i < N; i++)
{
if (array[i] != i + 1)
{
count++;
}
}
return count;
}
static bool CheckSorted( int N, int [] A)
{
int count = FindUnsortedCount(A, N);
if (count == 0 || count == 3)
{
return true ;
}
if (count == 4)
{
SwapOne(A, N);
SwapOne(A, N);
return FindUnsortedCount(A, N) == 0;
}
return false ;
}
static void Main()
{
int N = 4;
int [] A = { 4, 3, 2, 1 };
bool isSorted = CheckSorted(N, A);
Console.WriteLine(isSorted);
}
}
|
Javascript
function swapOne(array, N) {
for (let i = 0; i < N; i++) {
if (array[i] !== i + 1) {
const temp = array[i];
array[i] = array[temp - 1];
array[temp - 1] = temp;
break ;
}
}
}
function findUnsortedCount(array, N) {
let count = 0;
for (let i = 0; i < N; i++) {
if (array[i] !== i + 1) {
count++;
}
}
return count;
}
function checkSorted(N, A) {
const count = findUnsortedCount(A, N);
if (count === 0 || count === 3) {
return true ;
}
if (count === 4) {
swapOne(A, N);
swapOne(A, N);
return findUnsortedCount(A, N) === 0;
}
return false ;
}
const N = 4;
const A = [4, 3, 2, 1];
const isSorted = checkSorted(N, A);
console.log(isSorted);
|
Time Complexity: O(N), We iterate through the array once.
Auxiliary space: O(1), We use a constant amount of additional space.
Share your thoughts in the comments
Please Login to comment...