text: Sort an array according to count of set bits | C # 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
code: using System ; using System . Collections . Generic ; 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 ) { List < Tuple < int , int > > count = new List < Tuple < int , int > > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { count . Add ( new Tuple < int , int > ( ( - 1 ) * setBitCount ( arr [ i ] ) , arr [ i ] ) ) ; } count . Sort ( ) ; foreach ( Tuple < int , int > i in count ) { Console . Write ( i . Item2 + " ▁ " ) ; } Console . WriteLine ( ) ; } static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = arr . Length ; sortBySetBitCount ( arr , n ) ; } }