Check if array can be sorted with one swap | CPP program to check if an array can be sorted with at - most one swap ; Create a sorted copy of original array ; Check if 0 or 1 swap required to get the sorted array ; Driver Program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkSorted ( int n , int arr [ ] ) { int b [ n ] ; for ( int i = 0 ; i < n ; i ++ ) b [ i ] = arr [ i ] ; sort ( b , b + n ) ; int ct = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] != b [ i ] ) ct ++ ; if ( ct == 0 ct == 2 ) return true ; else return false ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkSorted ( n , arr ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }