# Sorting array elements with set bits equal to K

Given an array of integers and a number . The task is to sort only those elements of the array whose total set bits are equal to K. Sorting must be done at their relative positions only without affecting any other elements.

**Examples**:

Input: arr[] = {32, 1, 9, 4, 64, 2}, K = 1Output: 1 2 9 4 32 64 All of the elements except 9 has exactly 1 bit set. So, all elements except 9 are sorted without affecting the position of 9 in the input array.Input: arr[] = {2, 15, 12, 1, 3, 9}, K = 2Output: 2 15 3 1 9 12

**Approach:**

- Initialise two empty vectors.
- Traverse the array, from left to right and check the set bits of each element.
- Here, C++ inbuilt function __builtin_popcount() to count setbits.
- In first vector, insert the index of all elements with set bits equal to K.
- In second vector, insert the elements with set bits equal to K.
- Sort the second vector.
- Now, we have the index of all elements with set bit equals to K in sorted order and also all of the elements with set bit as K in sorted order.
- So, insert the elements of the second vector into the array at the indices present in first vector one by one.

Below is the implementation of the above approach:

## C++

`// C++ program for sorting array elements ` `// with set bits equal to K ` ` ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Function to sort elements with ` `// set bits equal to k ` `void` `sortWithSetbits(` `int` `arr[], ` `int` `n, ` `int` `k) ` `{ ` ` ` `// initialise two vectors ` ` ` `vector<` `int` `> v1, v2; ` ` ` ` ` `for` `(` `int` `i = 0; i < n; i++) { ` ` ` `if` `(__builtin_popcount(arr[i]) == k) { ` ` ` ` ` `// first vector contains indices of ` ` ` `// required element ` ` ` `v1.push_back(i); ` ` ` ` ` `// second vector contains ` ` ` `// required elements ` ` ` `v2.push_back(arr[i]); ` ` ` `} ` ` ` `} ` ` ` ` ` `// sorting the elements in second vector ` ` ` `sort(v2.begin(), v2.end()); ` ` ` ` ` `// replacing the elements with k set bits ` ` ` `// with the sorted elements ` ` ` `for` `(` `int` `i = 0; i < v1.size(); i++) ` ` ` `arr[v1[i]] = v2[i]; ` ` ` ` ` `// printing the new sorted array elements ` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `cout << arr[i] << ` `" "` `; ` `} ` ` ` `// Driver code ` `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; ` `} ` |

*chevron_right*

*filter_none*

## Python3

# Python 3 program for sorting array

# elements with set bits equal to K

# Function to sort elements with

# set bits equal to k

def sortWithSetbits(arr, n, k):

# initialise two vectors

v1 = []

v2 = []

for i in range(0, n, 1):

if (bin(arr[i]).count(‘1’) == k):

# first vector contains indices

# of required element

v1.append(i)

# second vector contains

# required elements

v2.append(arr[i])

# sorting the elements in second vector

v2.sort(reverse = False)

# replacing the elements with k set

# bits with the sorted elements

for i in range(0, len(v1), 1):

arr[v1[i]] = v2[i]

# printing the new sorted array elements

for i in range(0, n, 1):

print(arr[i], end = ” “)

# Driver code

if __name__ == ‘__main__’:

arr = [14, 255, 1, 7, 13]

n = len(arr)

k = 3

sortWithSetbits(arr, n, k)

# This code is contributed by

# Surendra_Gangwar

**Output:**

7 255 1 13 14

## Recommended Posts:

- XOR of all elements of array with set bits equal to K
- Count pairs in an array such that both elements has equal set bits
- Sorting all array elements except one
- Sorting array except elements in a subarray
- Sorting Array Elements By Frequency | Set 3 (Using STL)
- Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
- Smallest power of 2 which is greater than or equal to sum of array elements
- Count of index pairs with equal elements in an array
- Minimum Increment / decrement to make array elements equal
- Noble integers in an array (count of greater elements is equal to value)
- Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k
- Sorting without comparison of elements
- Count minimum bits to flip such that XOR of A and B equal to C
- Count elements such that there are exactly X elements with values greater than or equal to X
- Sorting array using Stacks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.