Sort an array according to count of set bits | Java program to implement simple approach to sort an array according to count of set bits . ; Function to count setbits ; Function to sort By SetBitCount ; Iterate over all values and insert into multimap ; Driver code
import java . io . * ; import java . util . * ; class GFG { static int setBitCount ( int num ) { int count = 0 ; while ( num != 0 ) { if ( ( num & 1 ) != 0 ) count ++ ; num >>= 1 ; } return count ; } static void sortBySetBitCount ( int [ ] arr , int n ) { ArrayList < ArrayList < Integer > > count = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { count . add ( new ArrayList < Integer > ( Arrays . asList ( ( - 1 ) * setBitCount ( arr [ i ] ) , arr [ i ] ) ) ) ; } Collections . sort ( count , new Comparator < ArrayList < Integer > > ( ) { @ Override public int compare ( ArrayList < Integer > o1 , ArrayList < Integer > o2 ) { return o1 . get ( 0 ) . compareTo ( o2 . get ( 0 ) ) ; } } ) ; for ( int i = 0 ; i < count . size ( ) ; i ++ ) { System . out . print ( count . get ( i ) . get ( 1 ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = arr . length ; sortBySetBitCount ( arr , n ) ; } }