text: Sort an array according to count of set bits | C # program to sort an array according to count of set bits using std :: sort ( ) ; a utility function that returns total set bits count in an integer ; Function to sort according to bit count . This function assumes that there are 32 bits in an integer . ; Used as an index in readonly sorted array ; Traverse through all bit counts ( Note that we sort array in decreasing order ) ; Utility function to print an array ; Driver Code
code: using System ; using System . Collections . Generic ; class GFG { static int countBits ( int a ) { int count = 0 ; while ( a > 0 ) { if ( ( a & 1 ) > 0 ) count += 1 ; a = a >> 1 ; } return count ; } static void sortBySetBitCount ( int [ ] arr , int n ) { List < int > [ ] count = new List < int > [ 32 ] ; for ( int i = 0 ; i < count . Length ; i ++ ) count [ i ] = new List < int > ( ) ; int setbitcount = 0 ; for ( int i = 0 ; i < n ; i ++ ) { setbitcount = countBits ( arr [ i ] ) ; count [ setbitcount ] . Add ( arr [ i ] ) ; } int j = 0 ; for ( int i = 31 ; i >= 0 ; i -- ) { List < int > v1 = count [ i ] ; for ( int p = 0 ; p < v1 . Count ; p ++ ) arr [ j ++ ] = v1 [ p ] ; } } static void printArr ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = arr . Length ; sortBySetBitCount ( arr , n ) ; printArr ( arr , n ) ; } }