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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CheckSort ( vector < int > arr , int k , int n ) { vector < int > sortarr ( arr . begin ( ) , arr . end ( ) ) ; sort ( sortarr . begin ( ) , sortarr . end ( ) ) ; if ( k == 1 ) printf ( " yes " ) ; else { int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { flag = 0 ; for ( int j = i ; j < n ; j += k ) { if ( sortarr [ i ] == arr [ j ] ) { swap ( arr [ i ] , arr [ j ] ) ; flag = 1 ; break ; } if ( j + k >= n ) break ; } if ( flag == 0 ) break ; } if ( flag == 0 ) printf ( " Not ▁ possible ▁ to ▁ sort " ) ; else printf ( " Possible ▁ to ▁ sort " ) ; } } int main ( ) { int k = 3 ; vector < int > arr = { 1 , 5 , 6 , 9 , 2 , 3 , 5 , 9 } ; int n = arr . size ( ) ; CheckSort ( arr , k , n ) ; return 0 ; }