Sorting array elements with set bits equal to K | C ++ program for sorting array elements with set bits equal to K ; 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 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sortWithSetbits ( int arr [ ] , int n , int k ) { vector < int > v1 , v2 ; for ( int i = 0 ; i < n ; i ++ ) { if ( __builtin_popcount ( arr [ i ] ) == k ) { v1 . push_back ( i ) ; v2 . push_back ( arr [ i ] ) ; } } sort ( v2 . begin ( ) , v2 . end ( ) ) ; for ( int i = 0 ; i < v1 . size ( ) ; i ++ ) arr [ v1 [ i ] ] = v2 [ i ] ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 14 , 255 , 1 , 7 , 13 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; sortWithSetbits ( arr , n , k ) ; return 0 ; }