Sorting array with conditional swapping | Function to check if it is possible to sort the array ; Calculating max_element at each iteration . ; if we can not swap the i - th element . ; if it is impossible to swap the max_element then we can not sort the array . ; Otherwise , we can sort the array . ; Driver Code
function possibleToSort ( arr , n , str ) { let max_element = - 1 ; for ( let i = 0 ; i < str . length ; i ++ ) { max_element = Math . max ( max_element , arr [ i ] ) ; if ( str [ i ] == ' ' ) { if ( max_element > i + 1 ) return " " ; } } return " " ; } let arr = [ 1 , 2 , 5 , 3 , 4 , 6 ] ; let n = arr . Length ; let str = " " ; document . write ( possibleToSort ( arr , n , str ) ) ;