Check if array can be sorted with one swap | Java 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 Code
import java . util . Arrays ; class GFG { static boolean checkSorted ( int n , int arr [ ] ) { int [ ] b = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) b [ i ] = arr [ i ] ; Arrays . sort ( b , 0 , 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 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 3 , 4 , 2 } ; int n = arr . length ; if ( checkSorted ( n , arr ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }