Check if the array can be sorted only if the elements on given positions can be swapped | Java program to check if the array can be sorted only if the elements on the 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
import java . util . Arrays ; class GFG { public static void check_vector ( int [ ] A , int n , int [ ] p ) { int [ ] pos = new int [ A . length ] ; for ( int i = 0 ; i < p . length ; i ++ ) { pos [ p [ i ] - 1 ] = 1 ; } int flag = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( pos [ i ] == 0 ) continue ; int j = i ; while ( j < n && pos [ j ] != 0 ) ++ j ; Arrays . sort ( A , i , j + 1 ) ; i = j ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { flag = 0 ; break ; } } if ( flag == 1 ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 2 , 1 } ; int p [ ] = { 1 , 2 } ; check_vector ( A , A . length , p ) ; } }