Check if it is possible to sort an array with conditional swapping of elements at distance K | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool fun ( int arr [ ] , int n , int k ) { vector < int > v ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = i ; j < n ; j += k ) { v . push_back ( arr [ j ] ) ; } sort ( v . begin ( ) , v . end ( ) ) ; int x = 0 ; for ( int j = i ; j < n ; j += k ) { arr [ j ] = v [ x ] ; x ++ ; } v . clear ( ) ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) return false ; } return true ; } int main ( ) { int arr [ ] = { 4 , 2 , 3 , 7 , 6 } ; int K = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( fun ( arr , n , K ) ) cout << " yes " << endl ; else cout << " no " << endl ; return 0 ; }