Check if array can be sorted with one swap | javascript 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
function checkSorted ( n , arr ) { var b = Array ( n ) . fill ( 0 ) ; for ( var i = 0 ; i < n ; i ++ ) b [ i ] = arr [ i ] ; b . sort ( ) ; var ct = 0 ; for ( var i = 0 ; i < n ; i ++ ) if ( arr [ i ] != b [ i ] ) ct ++ ; if ( ct == 0 ct == 2 ) return true ; else return false ; } var arr = [ 1 , 5 , 3 , 4 , 2 ] ; var n = arr . length ; if ( checkSorted ( n , arr ) ) document . write ( " " ) ; else document . write ( " " ) ;