Find if array can be sorted by swaps limited to multiples of k |  ; CheckSort function To check if array can be sorted ; sortarr is sorted array of arr ; If k = 1 then ( always possible to sort ) swapping can easily give sorted array ; Comparing sortarray with array ; Element at index j must be in j = i + l * k form where i = 0 , 1 , 2 , 3. . . where l = 0 , 1 , 2 , 3 , . . n - 1 ; If element is present then swapped ; If element of sorted array does not found in its sequence then flag remain zero that means arr can not be sort after swapping ; If flag is 0 Not possible else Possible ; Driver code ; Size of step ; Array initialized ; Length of arr ; Calling function
import java . util . * ; class GFG { public static void CheckSort ( Vector < Integer > arr , int k , int n ) { Vector < Integer > sortarr = new Vector < Integer > ( ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { sortarr . add ( arr . get ( i ) ) ; } Collections . sort ( sortarr ) ; if ( k == 1 ) System . out . println ( " yes " ) ; else { int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { flag = 0 ; for ( int j = i ; j < n ; j += k ) { if ( sortarr . get ( i ) == arr . get ( j ) ) { Collections . swap ( arr , i , j ) ; flag = 1 ; break ; } if ( j + k >= n ) break ; } if ( flag == 0 ) break ; } if ( flag == 0 ) System . out . println ( " Not ▁ possible ▁ to ▁ sort " ) ; else System . out . println ( " Possible ▁ to ▁ sort " ) ; } } public static void main ( String [ ] args ) { int k = 3 ; Vector < Integer > arr = new Vector < Integer > ( ) ; arr . add ( 1 ) ; arr . add ( 5 ) ; arr . add ( 6 ) ; arr . add ( 9 ) ; arr . add ( 2 ) ; arr . add ( 3 ) ; arr . add ( 5 ) ; arr . add ( 9 ) ; int n = arr . size ( ) ; CheckSort ( arr , k , n ) ; } }