Open In App

Check if it is possible to sort the array without swapping adjacent elements

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, check if it is possible to sort arr[] without swapping adjacent elements. In other words, check if it is possible to sort arr[] by swapping elements but swapping two consecutive element is not allowed.

Examples:

Input: N = 4, arr[] = {2, 3, 1, 4}
Output: YES
Explanation:

  • Swap arr[0] and arr[3], so arr[] becomes {4, 3, 1, 2}.
  • Swap arr[1] and arr[3] so arr[] becomes {4, 2, 1, 3}.
  • Swap arr[0] and arr[3] so arr[] becomes {3, 2, 1, 4}.
  • Swap arr[0] and arr[2], so arr[] becomes {1, 2, 3, 4}.

Input: N = 2, arr[] = {3, 2}
Output: No
Explanation: It is not allowed to swap consecutive elements, so we cannot change the order of arr[].

Approach: To solve the problem, follow the below idea:

For N = 1: The input array arr[] is already sorted.

For N = 2: If the input array arr[] is not sorted already, then it is impossible to sort the array as adjacent swaps are not allowed.

For N = 3: Since adjacent swaps are not allowed, it is impossible to change the position of the middle element. So, if the middle element is already in it’s correct position, then it is possible to sort the array. Otherwise, it is impossible to sort the array.

For N = 4: For a given arr[] of size 4, say arr[] = {a, b, c, d}. So, if we observe carefully, then it is always possible to construct all the possible permutation of arr[] without swapping any adjacent elements.

For N > 4: Since, we can generate all the possible permutation of size 4 without swapping adjacent elements, so we can also generate all the possible permutations of size 5.

So, for all array having > 3 elements, it is always possible to sort the array.

Below is the implementation of the approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to print if array is possible to sort or not
void solve(int arr[], int N)
{
    // If N = 2 and arr[] is not sorted in ascending order,
    // then it is impossible to sort the array
    if (N == 2 && arr[1] < arr[0]) {
        cout << "NO" << endl;
    }
    // If N = 3 and arr[1] is not at its correct position,
    // then it is impossible to sort the array
    else if (N == 3
             && (arr[1] < min(arr[0], arr[2])
                 || arr[1] > max(arr[0], arr[2]))) {
        cout << "NO" << endl;
    }
    else {
        cout << "YES" << endl;
    }
}

// Driver Code
int main()
{
    // Sample Input
    int N = 4;
    int arr[] = { 2, 3, 1, 4 };

    solve(arr, N);
    return 0;
}
Java
import java.util.Arrays;

public class Main {
    // Function to print if the array is possible to sort or not
    static void solve(int[] arr, int N) {
        // If N = 2 and arr[] is not sorted in ascending order,
        // then it is impossible to sort the array
        if (N == 2 && arr[1] < arr[0]) {
            System.out.println("NO");
        }
        // If N = 3 and arr[1] is not at its correct position,
        // then it is impossible to sort the array
        else if (N == 3 && (arr[1] < Math.min(arr[0], arr[2]) || arr[1] > Math.max(arr[0], arr[2]))) {
            System.out.println("NO");
        } else {
            System.out.println("YES");
        }
    }

    public static void main(String[] args) {
        // Sample Input
        int N = 4;
        int[] arr = {2, 3, 1, 4};

        solve(arr, N);
    }
}

// This code is contributed by shivamgupta0987654321
Python3
# Function to print if array is possible to sort or not
def solve(arr):
    N = len(arr)
    # If N = 2 and arr[] is not sorted in ascending order,
    # then it is impossible to sort the array
    if N == 2 and arr[1] < arr[0]:
        print("NO")
    # If N = 3 and arr[1] is not at its correct position,
    # then it is impossible to sort the array
    elif N == 3 and (arr[1] < min(arr[0], arr[2]) or arr[1] > max(arr[0], arr[2])):
        print("NO")
    else:
        print("YES")

# Driver Code
if __name__ == "__main__":
    # Sample Input
    arr = [2, 3, 1, 4]
    solve(arr)
JavaScript
// Function to print if array is possible to sort or not
function solve(arr) {
    const N = arr.length;
    // If N = 2 and arr[] is not sorted in ascending order,
    // then it is impossible to sort the array
    if (N === 2 && arr[1] < arr[0]) {
        console.log("NO");
    } 
    // If N = 3 and arr[1] is not at its correct position,
    // then it is impossible to sort the array
    else if (N === 3 && (arr[1] < Math.min(arr[0], arr[2]) || arr[1] > Math.max(arr[0], arr[2]))) {
        console.log("NO");
    } 
    else {
        console.log("YES");
    }
}

// Driver Code
// Sample Input
const arr = [2, 3, 1, 4];
solve(arr);

Output
YES

Time Complexity: O(1)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads