Sorting array elements with set bits equal to K | C # program for sorting array elements with set bits equal to K ; Represents node of a doubly linked list ; Function to sort elements with set bits equal to k ; initialise two vectors ; first vector contains indices of required element ; second vector contains required elements ; sorting the elements in second vector ; replacing the elements with k set bits with the sorted elements ; printing the new sorted array elements ; Utility function ; Driver code
using System ; using System . Collections . Generic ; public class Node { static void sortWithSetbits ( int [ ] arr , int n , int k ) { List < int > v1 = new List < int > ( ) ; List < int > v2 = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( bitCount ( arr [ i ] ) == k ) { v1 . Add ( i ) ; v2 . Add ( arr [ i ] ) ; } } v2 . Sort ( ) ; for ( int i = 0 ; i < v1 . Count ; i ++ ) { arr [ v1 [ i ] ] = v2 [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( arr [ i ] + " ▁ " ) ; } } static int bitCount ( long x ) { int setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } public static void Main ( String [ ] args ) { int [ ] arr = { 14 , 255 , 1 , 7 , 13 } ; int n = arr . Length ; int k = 3 ; sortWithSetbits ( arr , n , k ) ; } }