Check if it is possible to sort an array with conditional swapping of adjacent allowed | Returns true if it is possible to sort else false ; We need to do something only if previousl element is greater ; If difference is more than one , then not possible ; Driver Code
function checkForSorting ( arr , n ) { let temp = 0 ; for ( let i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) { if ( arr [ i ] - arr [ i + 1 ] == 1 ) { temp = arr [ i ] ; arr [ i ] = arr [ i + 1 ] ; arr [ i + 1 ] = temp ; } else return false ; } } return true ; } let arr = new Array ( 1 , 0 , 3 , 2 ) ; let n = arr . length ; if ( checkForSorting ( arr , n ) ) document . write ( " " ) ; else document . write ( " " ) ;