Check if the array can be sorted only if the elements on given positions can be swapped | Function to check if the array can be sorted only if the elements on the given positions can be swapped ; Creating an array for marking the positions ; Iterating through the array and mark the positions ; Iterating through the given array ; If pos [ i ] is 1 , then incrementing till 1 is continuously present in pos ; Sorting the required segment ; Checking if the vector is sorted or not ; Print yes if it is sorted ; Driver code
function check_vector ( A , n , p ) { var pos = A . length ; for ( var i = 0 ; i < p . length ; i ++ ) { pos [ p [ i ] - 1 ] = 1 ; } var flag = 1 ; for ( var i = 0 ; i < n ; i ++ ) { if ( pos [ i ] == 0 ) continue ; var j = i ; while ( j < n && pos [ j ] ) ++ j ; A = Array . prototype . concat ( A . slice ( 0 , i ) , A . slice ( i + 1 , j + 1 ) . sort ( ( a , b ) => a - b ) , A . slice ( j + 2 ) . sort ( ( a , b ) => a - b ) ) ; i = j ; } for ( var i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { flag = 0 ; break ; } } if ( flag == 1 ) document . write ( " " ) ; else document . write ( " " ) ; } var A = [ 3 , 2 , 1 ] ; var p = [ 1 , 2 ] ; check_vector ( A , A . length , p ) ;