human
Give me a code to sort an array according to count of set bits and the other steps required given the following:
Sort an array according to count of set bits | a utility function that returns total set bits count in an integer.
Function to simultaneously sort both arrays using insertion sort ( http : quiz . geeksforgeeks . org / insertion - sort / ).
use 2 keys because we need to sort both arrays simultaneously.
Move elements of arr [ 0. . i - 1 ] and aux [ 0. . i - 1 ] , such that elements of aux [ 0. . i - 1 ] are greater than key1 , to one position ahead of their current position.
Function to sort according to bit count using an auxiliary array.
Create an array and store count of set bits in it ..
Sort arr [ ] according to values in aux [ ].
Utility function to print an array.
Driver Code"
Solution in Python:
assistant
#Here is code to sort an array according to count of set bits and the other steps required.
 def countBits ( a ) :
	count = 0
	while ( a ) :
		if ( a & 1 ) :
			count += 1
		a = a >> 1
	return count
def insertionSort ( arr , aux , n ) :
	for i in range ( 1 , n , 1 ) :
		key1 = aux [ i ]
		key2 = arr [ i ]
		j = i - 1
		while ( j >= 0 and aux [ j ] < key1 ) :
			aux [ j + 1 ] = aux [ j ]
			arr [ j + 1 ] = arr [ j ]
			j = j - 1
		aux [ j + 1 ] = key1
		arr [ j + 1 ] = key2
def sortBySetBitCount ( arr , n ) :
	aux = [ 0 for i in range ( n ) ]
	for i in range ( 0 , n , 1 ) :
		aux [ i ] = countBits ( arr [ i ] )
	insertionSort ( arr , aux , n )
def printArr ( arr , n ) :
	for i in range ( 0 , n , 1 ) :
		print ( arr [ i ] , end = " ▁ " )
if __name__ == ' _ _ main _ _ ' :
	arr = [ 1 , 2 , 3 , 4 , 5 , 6 ]
	n = len ( arr )
	sortBySetBitCount ( arr , n )
	printArr ( arr , n )