Sorting array elements with set bits equal to K | Java 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 ; Driver code
import java . util . * ; class Node { static void sortWithSetbits ( int arr [ ] , int n , int k ) { Vector < Integer > v1 = new Vector < > ( ) , v2 = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( Integer . bitCount ( arr [ i ] ) == k ) { v1 . add ( i ) ; v2 . add ( arr [ i ] ) ; } } Collections . sort ( v2 ) ; for ( int i = 0 ; i < v1 . size ( ) ; i ++ ) { arr [ v1 . get ( i ) ] = v2 . get ( i ) ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 14 , 255 , 1 , 7 , 13 } ; int n = arr . length ; int k = 3 ; sortWithSetbits ( arr , n , k ) ; } }