VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-it-is-possible-to-sort-the-array-without-swapping-adjacent-elements/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 9 Apr, 2024

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:


Output
YES

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

Comment
Article Tags: