Open In App

Sorting Array with Two Swaps

Last Updated : 08 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// CPP code for the above approach
#include <iostream>
using namespace std;
 
// Function to swap an element to its correct position
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;
        }
    }
}
 
// Function to find the count of unsorted elements
int findUnsortedCount(int array[], int N)
{
    // Count the number of elements which are not at their
    // correct position
    int count = 0;
    for (int i = 0; i < N; i++) {
        if (array[i] != i + 1) {
            count++;
        }
    }
    return count;
}
 
// Function to check if the array is sorted
bool checkSorted(int N, int A[])
{
    int count = findUnsortedCount(A, N);
 
    if (count == 0 || count == 3) {
        return true;
    }
 
    if (count == 4) {
        // Swap twice and check whether the array is sorted.
        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;
}
 
// This code is contributed by Susobhan Akhuli


Java




// Java code for the above approach:
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) {
 
            // Swap twice and check whether
            // the array is sorted.
            swapOne(A);
            swapOne(A);
            return findUnsortedCount(A) == 0;
        }
 
        return false;
    }
 
    static int findUnsortedCount(int[] array)
    {
 
        // Count the number of elements which
        // are not at their correct position
        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




# Python code for the above approach
def check_sorted(N, A):
    count = find_unsorted_count(A)
 
    if count == 0 or count == 3:
        return True
 
    if count == 4:
        # Swap twice and check whether
        # the array is sorted.
        swap_one(A)
        swap_one(A)
        return find_unsorted_count(A) == 0
 
    return False
 
def find_unsorted_count(array):
    # Count the number of elements which
    # are not at their correct position
    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
{
    // Function to swap an element to its correct position
    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;
            }
        }
    }
    // Function to find the count of the unsorted elements
    static int FindUnsortedCount(int[] array, int N)
    {
        // Count the number of the elements which are not at their
        // correct position
        int count = 0;
        for (int i = 0; i < N; i++)
        {
            if (array[i] != i + 1)
            {
                count++;
            }
        }
        return count;
    }
    // Function to check if the array is sorted
    static bool CheckSorted(int N, int[] A)
    {
        int count = FindUnsortedCount(A, N);
 
        if (count == 0 || count == 3)
        {
            return true;
        }
        if (count == 4)
        {
            // Swap twice and check whether the array is sorted.
            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




// JavaScript Implementation of the given problem
 
// Function to swap an element to its correct position
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 to find the count of unsorted elements
function findUnsortedCount(array, N) {
    let count = 0;
    for (let i = 0; i < N; i++) {
        if (array[i] !== i + 1) {
            count++;
        }
    }
    return count;
}
 
// Function to check if the array is sorted
function checkSorted(N, A) {
    const count = findUnsortedCount(A, N);
 
    if (count === 0 || count === 3) {
        return true;
    }
 
    if (count === 4) {
        // Swap twice and check whether the array is sorted.
        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);


Output

true










Time Complexity: O(N), We iterate through the array once.
Auxiliary space: O(1), We use a constant amount of additional space.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads