Sort elements of the array that occurs in between multiples of K | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function to sort elements in between multiples of k ; To store the index of previous multiple of k ; If it is not the first multiple of k ; Sort the elements in between the previous and the current multiple of k ; Update previous to be current ; Print the updated array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << ( arr [ i ] ) << " ▁ " ; } void sortArr ( int arr [ ] , int n , int k ) { int prev = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) { if ( prev != -1 ) sort ( arr + prev + 1 , arr + i ) ; prev = i ; } } printArr ( arr , n ) ; } int main ( ) { int arr [ ] = { 2 , 1 , 13 , 3 , 7 , 8 , 21 , 13 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; sortArr ( arr , n , k ) ; }