Sort elements by modulo with K | Utility function to prlet 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 ; Prlet the sorted array ; Driver code
function prletArr ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } function sortWithRemainder ( arr , n , k ) { let v = new Array ( ) ; for ( let i = 0 ; i < k ; i ++ ) { v . push ( [ ] ) } for ( let i = 0 ; i < n ; i ++ ) { v [ arr [ i ] % k ] . push ( arr [ i ] ) ; } for ( let i = 0 ; i < k ; i ++ ) v [ i ] . sort ( ( a , b ) => a - b ) ; console . log ( v ) let j = 0 ; for ( let i = 0 ; i < k ; i ++ ) { for ( let it of v [ i ] ) { arr [ j ] = it ; j ++ ; } } prletArr ( arr , n ) ; } let arr = [ 10 , 7 , 2 , 6 , 12 , 3 , 33 , 46 ] ; let n = arr . length ; let k = 4 ; sortWithRemainder ( arr , n , k ) ;