Sorting array elements with set bits equal to K
Last Updated :
29 Jun, 2022
Given an array of integers and a number K . 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 = 1
Output : 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 = 2
Output : 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;
}
Java
// Java program for sorting array elements
// with set bits equal to K
import java.util.*;
// Represents node of a doubly linked list
class Node
{
// Function to sort elements with
// set bits equal to k
static void sortWithSetbits(int arr[], int n, int k)
{
// initialise two vectors
Vector<Integer> v1 = new Vector<>(), v2 = new Vector<>();
for (int i = 0; i < n; i++) {
if (Integer.bitCount(arr[i]) == k)
{
// first vector contains indices of
// required element
v1.add(i);
// second vector contains
// required elements
v2.add(arr[i]);
}
}
// sorting the elements in second vector
Collections.sort(v2);
// replacing the elements with k set bits
// with the sorted elements
for (int i = 0; i < v1.size(); i++)
{
arr[v1.get(i)] = v2.get(i);
}
// printing the new sorted array elements
for (int i = 0; i < n; i++)
{
System.out.print(arr[i] + " ");
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = {14, 255, 1, 7, 13};
int n = arr.length;
int k = 3;
sortWithSetbits(arr, n, k);
}
}
// This code is contributed by Princi Singh
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
C#
// C# program for sorting array elements
// with set bits equal to K
using System;
using System.Collections.Generic;
// Represents node of a doubly linked list
public class Node
{
// Function to sort elements with
// set bits equal to k
static void sortWithSetbits(int []arr, int n, int k)
{
// initialise two vectors
List<int> v1 = new List<int>();
List<int> v2 = new List<int>();
for (int i = 0; i < n; i++)
{
if (bitCount(arr[i]) == k)
{
// first vector contains indices of
// required element
v1.Add(i);
// second vector contains
// required elements
v2.Add(arr[i]);
}
}
// sorting the elements in second vector
v2.Sort();
// replacing the elements with k set bits
// with the sorted elements
for (int i = 0; i < v1.Count; i++)
{
arr[v1[i]] = v2[i];
}
// printing the new sorted array elements
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;
}
// Driver code
public static void Main(String[] args)
{
int []arr = {14, 255, 1, 7, 13};
int n = arr.Length;
int k = 3;
sortWithSetbits(arr, n, k);
}
}
/* This code is contributed by PrinciRaj1992 */
JavaScript
<script>
// Javascript program for sorting array elements
// with set bits equal to K
function bitCount(x)
{
var setBits = 0;
while (x != 0)
{
x = x & (x - 1);
setBits++;
}
return setBits;
}
// Function to sort elements with
// set bits equal to k
function sortWithSetbits(arr, n, k)
{
// initialise two vectors
var v1 = [], v2 = [];
for (var i = 0; i < n; i++) {
if (bitCount(arr[i]) == k) {
// first vector contains indices of
// required element
v1.push(i);
// second vector contains
// required elements
v2.push(arr[i]);
}
}
// sorting the elements in second vector
v2.sort((a,b)=> a-b);
// replacing the elements with k set bits
// with the sorted elements
for (var i = 0; i < v1.length; i++)
arr[v1[i]] = v2[i];
// printing the new sorted array elements
for (var i = 0; i < n; i++)
document.write( arr[i] + " ");
}
// Driver code
var arr = [14, 255, 1, 7, 13 ];
var n = arr.length;
var k = 3;
sortWithSetbits(arr, n, k);
</script>
Time Complexity: O(n*log(n))
Auxiliary Space: O(n)
Similar Reads
XOR of all elements of array with set bits equal to K Given an array of integers and a number K. The task is to find the XOR of only those elements of the array whose total set bits are equal to K. Examples: Input : arr[] = {1, 22, 3, 10}, K=1 Output : 1 Elements with set bits equal to 1 is 1. So, XOR is also 1. Input : arr[] = {3, 4, 10, 5, 8}, K=2 Ou
4 min read
Minimum Bitwise OR operations to make any two array elements equal Given an array arr[] of integers and an integer K, we can perform the Bitwise OR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two eleme
9 min read
Queries for number of array elements in a range with Kth Bit Set Given an array of N positive (32-bit)integers, the task is to answer Q queries of the following form: Query(L, R, K): Print the number of elements of the array in the range L to R, which have their Kth bit as set Note: Consider LSB to be indexed at 1. Examples: Input : arr[] = { 8, 9, 1, 3 } Query 1
15+ min read
Sorting all array elements except one Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted. Examples: Input : arr[] = {10, 4, 11, 7, 6, 20} k = 2; Output : arr[] = {4, 6, 11, 7, 10, 20} Input : arr[] = {30, 20, 10} k =
6 min read
Largest set with bitwise OR equal to n Given an integer n, find the largest possible set of non-negative integers with bitwise OR equal to n.Examples: Input : n = 5 Output : arr[] = [0, 1, 4, 5] The bitwise OR of 0, 1, 4 and 5 equals 5. It is not possible to obtain a set larger than this. Input : n = 8 Output : arr[] = [0, 8] Prerequisit
5 min read
Sort elements by modulo with K Given an array, arr[] of integers and an integer K. The task is to sort the elements of the given array in the increasing order of their modulo with K. If two numbers have the same remainder then the smaller number should come first. Examples: Input: arr[] = {10, 3, 2, 6, 12}, K = 4 Output: 12 2 6 1
7 min read
Find the Kth smallest element in the sorted generated array Given an array arr[] of N elements and an integer K, the task is to generate an B[] with the following rules: Copy elements arr[1...N], N times to array B[].Copy elements arr[1...N/2], 2*N times to array B[].Copy elements arr[1...N/4], 3*N times to array B[].Similarly, until only no element is left
8 min read
Maximum subset with bitwise OR equal to k Given an array of non-negative integers and an integer k, find the subset of maximum length with bitwise OR equal to k. Examples: Input : arr[] = [1, 4, 2] k = 3 Output : [1, 2] Explanation: The bitwise OR of 1 and 2 equals 3. It is not possible to obtain a subset of length greater than 2. Input : a
8 min read
Sort elements of the array that occurs in between multiples of K Given an array arr[] and an integer K. The task is to sort the elements that are in between any two multiples of K. Examples: Input: arr[] = {2, 1, 13, 3, 7, 8, 21, 13, 12}, K = 2 Output: 2 1 3 7 13 8 13 21 12 The multiples of 2 in the array are 2, 8 and 12. The elements that are in between the firs
6 min read
Kâth Smallest Element in Unsorted Array Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples:Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content[Naive Ap
15 min read