Sort elements by modulo with K | C # implementation of the above 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
using System ; using System . Collections ; class GFG { static void printArr ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } static void sortWithRemainder ( int [ ] arr , int n , int k ) { ArrayList [ ] v = new ArrayList [ k ] ; for ( int i = 0 ; i < k ; i ++ ) { v [ i ] = new ArrayList ( ) ; } for ( int i = 0 ; i < n ; i ++ ) { v [ arr [ i ] % k ] . Add ( arr [ i ] ) ; } for ( int i = 0 ; i < k ; i ++ ) { v [ i ] . Sort ( ) ; } int j = 0 ; for ( int i = 0 ; i < k ; i ++ ) { foreach ( int x in v [ i ] ) { arr [ j ] = x ; j ++ ; } } printArr ( arr , n ) ; } public static void Main ( string [ ] args ) { int [ ] arr = { 10 , 7 , 2 , 6 , 12 , 3 , 33 , 46 } ; int n = arr . Length ; int k = 4 ; sortWithRemainder ( arr , n , k ) ; } }