Sort elements by modulo with K | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function to sort the array elements based on their modulo with K ; Create K empty vectors ; Update the vectors such that v [ i ] will contain all the elements that give remainder as i when divided by k ; Sorting all the vectors separately ; Replacing the elements in arr [ ] with the required modulo sorted elements ; Add all the elements of the current vector to the array ; Print the sorted 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 sortWithRemainder ( int arr [ ] , int n , int k ) { vector < int > v [ k ] ; for ( int i = 0 ; i < n ; i ++ ) { v [ arr [ i ] % k ] . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < k ; i ++ ) sort ( v [ i ] . begin ( ) , v [ i ] . end ( ) ) ; int j = 0 ; for ( int i = 0 ; i < k ; i ++ ) { for ( vector < int > :: iterator it = v [ i ] . begin ( ) ; it != v [ i ] . end ( ) ; it ++ ) { arr [ j ] = * it ; j ++ ; } } printArr ( arr , n ) ; } int main ( ) { int arr [ ] = { 10 , 7 , 2 , 6 , 12 , 3 , 33 , 46 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 4 ; sortWithRemainder ( arr , n , k ) ; return 0 ; }