Sort elements by modulo with K | Java 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
import java . util . * ; class GFG { static void printArr ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void sortWithRemainder ( int [ ] arr , int n , int k ) { ArrayList < ArrayList < Integer > > v = new ArrayList < ArrayList < Integer > > ( k ) ; for ( int i = 0 ; i < k ; i ++ ) v . add ( new ArrayList < Integer > ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { int t = arr [ i ] % k ; v . get ( t ) . add ( arr [ i ] ) ; } for ( int i = 0 ; i < k ; i ++ ) { Collections . sort ( v . get ( i ) ) ; } int j = 0 ; for ( int i = 0 ; i < k ; i ++ ) { for ( int x : v . get ( 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 ) ; } }