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++
// 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);
Time Complexity: O(N), We iterate through the array once.
Auxiliary space: O(1), We use a constant amount of additional space.
Similar Reads
Minimum swaps to sort an array Given an array arr[] of distinct elements, find the minimum number of swaps required to sort the array.Examples: Input: arr[] = [2, 8, 5, 4]Output: 1Explanation: Swap 8 with 4 to get the sorted array.Input: arr[] = [10, 19, 6, 3, 5]Output: 2Explanation: Swap 10 with 3 and 19 with 5 to get the sorted
10 min read
Merge Two Sorted Arrays Without Extra Space Given two sorted arrays a[] and b[] of size n and m respectively, the task is to merge both the arrays and rearrange the elements such that the smallest n elements are in a[] and the remaining m elements are in b[]. All elements in a[] and b[] should be in sorted order.Examples: Input: a[] = [2, 4,
15+ min read
Check if array can be sorted with one swap 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} Out
11 min read
Minimum Operations to Sort Array with Custom Shuffling Given an array A[] of length N along with a string S, the task is to output the minimum number of operations required to sort A[]. If it's not possible then output -1. You can apply the below operation on A[] using S as follows: Choose two distinct indices let's say i and j such that (i != j) and S[
12 min read
Bubble sort using two Stacks Prerequisite : Bubble Sort Write a function that sort an array of integers using stacks and also uses bubble sort paradigm. Algorithm: 1. Push all elements of array in 1st stack 2. Run a loop for 'n' times(n is size of array) having the following : 2.a. Keep on pushing elements in the 2nd stack till
6 min read
Number of swaps to sort when only adjacent swapping allowed Given an array arr[] of non negative integers. We can perform a swap operation on any two adjacent elements in the array. Find the minimum number of swaps needed to sort the array in ascending order. Examples : Input : arr[] = {3, 2, 1}Output : 3We need to do following swaps (3, 2), (3, 1) and (1, 2
13 min read
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[1] and B[1], both the arrays are sorted. Input : A[ ]={ 1, 4, 5, 5, 7}, B[ ]={ 2, 2,
12 min read
Count swaps required to sort an array using Insertion Sort Given an array A[] of size N (1 ⤠N ⤠105), the task is to calculate the number of swaps required to sort the array using insertion sort algorithm.Examples:Input: A[] = {2, 1, 3, 1, 2} Output: 4 Explanation:Step 1: arr[0] stays in its initial position. Step 2: arr[1] shifts 1 place to the left. Coun
15 min read
Swap Two Numbers Given two numbers a and b, the task is to swap them.Examples: Input: a = 2, b = 3Output: a = 3, b = 2Input: a = 20, b = 0Output: a = 0, b = 20Input: a = 10, b = 10Output: a = 10, b = 10 Table of Content[Naive Approach] Using Third Variable[Expected Approach] Without using Third Variable[Alternate Ap
4 min read
Sort an array with swapping only with a special element is allowed Given an array of length n + 1, containing elements 1 through n and a space, Requires the use of a given swap (index i, index j) function to sort the array, You can only swap the gap and a number, in the end, put the gap at the end. There will be a number 999 in the array as a gap or space. Examples
10 min read