Check if it is possible to sort an array with conditional swapping of elements at distance K | Java implementation to check if it is possible to sort an array with conditional swapping of elements at distance K ; Function for finding if it possible to obtain sorted array or not ; Iterate over all elements until K ; Store elements as multiples of K ; Sort the elements ; Put elements in their required position ; Check if the array becomes sorted or not ; Driver code
import java . lang . * ; import java . io . * ; import java . util . * ; class GFG { public static boolean fun ( int [ ] arr , int n , int k ) { Vector < Integer > v = new Vector < Integer > ( ) ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = i ; j < n ; j += k ) { v . add ( arr [ j ] ) ; } Collections . sort ( v ) ; int x = 0 ; for ( int j = i ; j < n ; j += k ) { arr [ j ] = v . get ( x ) ; x ++ ; } v . clear ( ) ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) { return false ; } } return true ; } public static void main ( String args [ ] ) { int [ ] arr = { 4 , 2 , 3 , 7 , 6 } ; int K = 2 ; int n = arr . length ; if ( fun ( arr , n , K ) ) { System . out . println ( " yes " ) ; } else { System . out . println ( " no " ) ; } } }