text: Check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array | Function to check if array , A can be converted into sorted array by swapping ( A [ i ] , A [ j ] ) if B [ i ] not equal to B [ j ] ; Stores if array A is sorted in descending order or not ; Traverse the array A ; If A [ i ] is greater than A [ i + 1 ] ; Update flag ; If array is sorted in ascending order ; count = 2 : Check if 0 s and 1 s both present in the B ; Traverse the array ; If current element is 0 ; Update count ; Traverse the array B ; If current element is 1 ; If both 0 s and 1 s are present in the array ; Input array A ; Input array B ; Function call ; If true , print YES ; Else print NO
code: function checkifSorted ( A , B , N ) { var flag = false ; for ( i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { flag = true ; break ; } } if ( ! flag ) { return true ; } var count = 0 ; for ( i = 0 ; i < N ; i ++ ) { if ( B [ i ] == 0 ) { count ++ ; break ; } } for ( i = 0 ; i < N ; i ++ ) { if ( B [ i ] == 1 ) { count ++ ; break ; } } if ( count == 2 ) { return true ; } return false ; } var A = [ 3 , 1 , 2 ] ; var B = [ 0 , 1 , 1 ] ; var N = A . length ; var check = checkifSorted ( A , B , N ) ; if ( check ) { document . write ( " " ) ; } else { document . write ( " " ) ; }