VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sorting-array-with-two-swaps/

⇱ Sorting Array with Two Swaps - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sorting Array with Two Swaps

Last Updated : 4 May, 2026

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: 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: a[] = [4, 3, 1, 2]
Output: false
Explanation: It's not possible to sort the array in two swaps.

We count how many elements are not in their correct positions (i.e., a[i] != i+1). Based on this count, we determine whether the array can be sorted using at most 2 swaps. If needed, we simulate up to 2 swaps and check if the array becomes sorted.

  • Count number of misplaced elements c
  • If c == 0, array is already sorted
  • If c == 3, it forms a cycle sortable in 2 swaps
  • If c == 4, try performing at most 2 swaps
  • For each swap, place element at its correct position
  • After swaps, check if array is sorted
  • Return true if sorted, else false

Output
true
Comment