Open In App

Sort an array according to count of set bits

Last Updated : 05 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of positive integers, sort the array in decreasing order of count of set bits in binary representations of array elements. For integers having the same number of set bits in their binary representation, sort according to their position in the original array i.e., a stable sort. For example, if the input array is {3, 5}, then the output array should also be {3, 5}. Note that both 3 and 5 have the same number set bits.

Examples:

Input: arr[] = {5, 2, 3, 9, 4, 6, 7, 15, 32};
Output: 15 7 5 3 9 6 2 4 32
Explanation:
The integers in their binary representation are:
    15 -1111
    7  -0111
    5  -0101
    3  -0011
    9  -1001
    6  -0110
    2  -0010
    4- -0100
    32 -10000
hence the non-increasing sorted order is:
{15}, {7}, {5, 3, 9, 6}, {2, 4, 32}

Input: arr[] = {1, 2, 3, 4, 5, 6};
Output: 3 5 6 1 2 4
Explanation:
    3  - 0011
    5  - 0101
    6  - 0110
    1  - 0001
    2  - 0010
    4  - 0100
hence the non-increasing sorted order is
{3, 5, 6}, {1, 2, 4}
Recommended Practice

Method 1: Simple

  1. Create an auxiliary array and store the set-bit counts of all integers in the aux array
  2. Simultaneously sort both arrays according to the non-increasing order of auxiliary array. (Note that we need to use a stable sort algorithm)
Before sort:
int arr[] = {1, 2, 3, 4, 5, 6};
int aux[] = {1, 1, 2, 1, 2, 2}
After sort:
arr = {3, 5, 6, 1, 2, 4}
aux = {2, 2, 2, 1, 1, 1}

Implementation:

C++




// C++ program to implement simple approach to sort an array
// according to count of set bits.
#include <bits/stdc++.h>
using namespace std;
 
// a utility function that returns total set bits count in an integer
int countBits(int a)
{
    int count = 0;
    while (a) {
        if (a & 1)
            count += 1;
        a = a >> 1;
    }
    return count;
}
 
// Function to simultaneously sort both arrays using insertion sort
void insertionSort(int arr[], int aux[], int n)
{
    for (int i = 1; i < n; i++) {
        // use 2 keys because we need to sort both arrays simultaneously
        int key1 = aux[i];
        int key2 = arr[i];
        int j = i - 1;
 
        // 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
        while (j >= 0 && aux[j] < key1) {
            aux[j + 1] = aux[j];
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        aux[j + 1] = key1;
        arr[j + 1] = key2;
    }
}
 
// Function to sort according to bit count using an auxiliary array
void sortBySetBitCount(int arr[], int n)
{
    // Create an array and store count of set bits in it.
    int aux[n];
    for (int i = 0; i < n; i++)
        aux[i] = countBits(arr[i]);
 
    // Sort arr[] according to values in aux[]
    insertionSort(arr, aux, n);
}
 
// Utility function to print an array
void printArr(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    sortBySetBitCount(arr, n);
    printArr(arr, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program to implement simple approach to sort an array
// according to count of set bits.
#include <stdio.h>
 
// a utility function that returns total set bits count in an integer
int countBits(int a)
{
    int count = 0;
    while (a) {
        if (a & 1)
            count += 1;
        a = a >> 1;
    }
    return count;
}
 
// Function to simultaneously sort both arrays using insertion sort
void insertionSort(int arr[], int aux[], int n)
{
    for (int i = 1; i < n; i++) {
        // use 2 keys because we need to sort both arrays simultaneously
        int key1 = aux[i];
        int key2 = arr[i];
        int j = i - 1;
 
        // 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
        while (j >= 0 && aux[j] < key1) {
            aux[j + 1] = aux[j];
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        aux[j + 1] = key1;
        arr[j + 1] = key2;
    }
}
 
// Function to sort according to bit count using an auxiliary array
void sortBySetBitCount(int arr[], int n)
{
    // Create an array and store count of set bits in it.
    int aux[n];
    for (int i = 0; i < n; i++)
        aux[i] = countBits(arr[i]);
 
    // Sort arr[] according to values in aux[]
    insertionSort(arr, aux, n);
}
 
// Utility function to print an array
void printArr(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    sortBySetBitCount(arr, n);
    printArr(arr, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program to implement simple approach to sort an
// array according to count of set bits.
import java.io.*;
 
class GFG {
 
    // utility function that returns total set bits count in an integer
    static int countBits(int a)
    {
        int count = 0;
        while (a > 0) {
            if ((a & 1) > 0)
                count += 1;
            a = a >> 1;
        }
        return count;
    }
 
    // Function to simultaneously sort both arrays using insertion sort
    static void insertionSort(int arr[], int aux[], int n)
    {
        for (int i = 1; i < n; i++) {
            // use 2 keys because we need to sort both
            // arrays simultaneously
            int key1 = aux[i];
            int key2 = arr[i];
            int j = i - 1;
 
            // 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
            while (j >= 0 && aux[j] < key1) {
                aux[j + 1] = aux[j];
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            aux[j + 1] = key1;
            arr[j + 1] = key2;
        }
    }
 
    // Function to sort according to bit count using an auxiliary array
    static void sortBySetBitCount(int arr[], int n)
    {
        // Create an array and store count of set bits in it.
        int aux[] = new int[n];
        for (int i = 0; i < n; i++)
            aux[i] = countBits(arr[i]);
 
        // Sort arr[] according to values in aux[]
        insertionSort(arr, aux, n);
    }
 
    // Utility function to print an array
    static void printArr(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5, 6 };
        int n = arr.length;
        sortBySetBitCount(arr, n);
        printArr(arr, n);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python 3 program to implement simple approach to sort
# an array according to count of set bits.
 
# a utility function that returns total set bits
# count in an integer
def countBits(a):
    count = 0
    while (a):
        if (a & 1):
            count+= 1
        a = a>>1
 
    return count
 
# Function to simultaneously sort both arrays
# using insertion sort
def insertionSort(arr,aux, n):
    for i in range(1,n,1):
        # use 2 keys because we need to sort both
        # arrays simultaneously
        key1 = aux[i]
        key2 = arr[i]
        j = i-1
 
        # 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 */
        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
 
# Function to sort according to bit count using
# an auxiliary array
def sortBySetBitCount(arr, n):
    # Create an array and store count of
    # set bits in it.
    aux = [0 for i in range(n)]
    for i in range(0,n,1):
        aux[i] = countBits(arr[i])
 
    # Sort arr[] according to values in aux[]
    insertionSort(arr, aux, n)
 
# Utility function to print an array
def printArr(arr, n):
    for i in range(0,n,1):
        print(arr[i],end = " ")
 
# Driver Code
if __name__ =='__main__':
    arr = [1, 2, 3, 4, 5, 6]
    n = len(arr)
    sortBySetBitCount(arr, n)
    printArr(arr, n)
 
# This code is contributed by
# Surendra_Gangwar


C#




// C# program to implement
// simple approach to sort
// an array according to
// count of set bits.
using System;
public class GFG
{
 
  // a utility function that
  // returns total set bits
  // count in an integer
  static int countBits(int a)
  {
    int count = 0;
    while (a > 0)
    {
      if ((a & 1) > 0)
        count += 1;
      a = a >> 1;
    }
    return count;
  }
 
  // Function to simultaneously
  // sort both arrays using
  // insertion sort
  // Function to simultaneously
  // sort both arrays using
  // insertion sort
  static void insertionSort(int []arr,
                            int []aux, int n)
  {
    for (int i = 1; i < n; i++)
    {
 
      // use 2 keys because we
      // need to sort both
      // arrays simultaneously
      int key1 = aux[i];
      int key2 = arr[i];
      int j = i - 1;
 
      /* 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 */
      while (j >= 0 && aux[j] < key1)
      {
        aux[j + 1] = aux[j];
        arr[j + 1] = arr[j];
        j = j - 1;
      }
      aux[j + 1] = key1;
      arr[j + 1] = key2;
    }
  }
 
  // Function to sort according
  // to bit count using an
  // auxiliary array
  static void sortBySetBitCount(int []arr,
                                int n)
  {
 
    // Create an array and
    // store count of
    // set bits in it.
    int []aux = new int[n];
    for (int i = 0; i < n; i++)
      aux[i] = countBits(arr[i]);
 
    // Sort arr[] according
    // to values in aux[]
    insertionSort(arr, aux, n);
  }
 
  // Utility function
  // to print an array
  static void printArr(int []arr, int n)
  {
    for (int i = 0; i < n; i++)
      Console.Write(arr[i] + " ");
  }
 
  // Driver Code
  static public void Main ()
  {
    int []arr = {1, 2, 3, 4, 5, 6};
    int n = arr.Length;
    sortBySetBitCount(arr, n);
    printArr(arr, n);
  }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript




<script>
 
// Javascript program to implement
// simple approach to sort
// an array according to
// count of set bits.
     
    // a utility function that
    // returns total set bits
    // count in an integer
    function countBits(a)
    {
        let count = 0;
    while (a > 0)
    {
        if ((a & 1) > 0)
            count+= 1;
        a = a >> 1;
    }
    return count;
    }
     
    // Function to simultaneously
// sort both arrays using
// insertion sort
function insertionSort(arr,aux,n)
{
    for (let i = 1; i < n; i++)
    {
        // use 2 keys because we
        // need to sort both
        // arrays simultaneously
        let key1 = aux[i];
        let key2 = arr[i];
        let j = i - 1;
  
        /* 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 */
        while (j >= 0 && aux[j] < key1)
        {
            aux[j + 1] = aux[j];
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        aux[j + 1] = key1;
        arr[j + 1] = key2;
    }
}
 
// Function to sort according
// to bit count using an
// auxiliary array
function sortBySetBitCount(arr,n)
{
    // Create an array and
    // store count of
    // set bits in it.
    let aux = new Array(n);
    for (let i = 0; i < n; i++)
        aux[i] = countBits(arr[i]);
  
    // Sort arr[] according
    // to values in aux[]
    insertionSort(arr, aux, n);
}
 
// Utility function
// to print an array
function printArr(arr,n)
{
    for (let i = 0; i < n; i++)
        document.write(arr[i] + " ");
}
 
// Driver Code
let arr=[1, 2, 3, 4, 5, 6];
let n = arr.length;
sortBySetBitCount(arr, n);
printArr(arr, n); 
     
    // This code is contributed by unknown2108
     
</script>


Output

3 5 6 1 2 4 

Auxiliary Space: O(n)
Time complexity: O(n2)

Note: Time complexity can be improved to O(nLogn) by using a stable O(nlogn) sorting algorithm.

Method 2: Using std::sort()

Using custom comparator of std::sort to sort the array according to set-bit count

C++




// C++ program to sort an array according to count of set
// bits using std::sort()
#include <bits/stdc++.h>
using namespace std;
 
// a utility function that returns total set bits count in an integer
int countBits(int a)
{
    int count = 0;
    while (a) {
        if (a & 1)
            count += 1;
        a = a >> 1;
    }
    return count;
}
 
// custom comparator of std::sort
int cmp(int a, int b)
{
    int count1 = countBits(a);
    int count2 = countBits(b);
 
    // this takes care of the stability of sorting algorithm too
    if (count1 <= count2)
        return false;
    return true;
}
 
// Function to sort according to bit count using std::sort
void sortBySetBitCount(int arr[], int n)
{
    stable_sort(arr, arr + n, cmp);
}
 
// Utility function to print an array
void printArr(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    sortBySetBitCount(arr, n);
    printArr(arr, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program to sort an array according to count of set bits
// using std::sort()
#include <stdio.h>
 
// a utility function that returns total set bits count in an integer
int countBits(int a)
{
    int count = 0;
    while (a) {
        if (a & 1)
            count += 1;
        a = a >> 1;
    }
    return count;
}
 
// custom comparator of std::sort
int cmp(int a, int b)
{
    int count1 = countBits(a);
    int count2 = countBits(b);
 
    // this takes care of the stability of sorting algorithm too
    if (count1 <= count2)
        return false;
    return true;
}
 
// Function to sort according to bit count using std::sort
void sortBySetBitCount(int arr[], int n)
{
    stable_sort(arr, arr + n, cmp);
}
 
// Utility function to print an array
void printArr(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    sortBySetBitCount(arr, n);
    printArr(arr, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program to sort an array according to count of set
// bits using std::sort()
import java.util.Arrays;
import java.util.Comparator;
 
public class Test {
 
    public static void main(String[] args)
    {
        Integer arr[] = { 1, 2, 3, 4, 5, 6 };
        int n = 6;
        sortBySetBitCount(arr, n);
        printArr(arr, n);
        System.out.println();
    }
 
    private static void printArr(Integer[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
 
    private static Integer[] sortBySetBitCount(
        Integer[] arr, int n)
    {
        Arrays.sort(arr, new Comparator<Integer>() {
            @Override
            public int compare(Integer arg0, Integer arg1)
            {
                int c1 = Integer.bitCount(arg0);
                int c2 = Integer.bitCount(arg1);
                if (c1 <= c2)
                    return 1;
                else
                    return -1;
            }
        });
        return arr;
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Using custom comparator lambda function
arr = [1, 2, 3, 4, 5, 6]
 
 
# form a tuple with val, index
n = len(arr)
arr = [(arr[i], i) for i in range(n)]
 
 
def countSetBits(val):
    cnt = 0
    while val:
        cnt += val % 2
        val = val//2
    return cnt
 
 
# first criteria to sort is number of set bits,
# then the index
sorted_arr = sorted(arr, key=lambda val: (
    countSetBits(val[0]), n-val[1]), reverse=True)
sorted_arr = [val[0] for val in sorted_arr]
print(sorted_arr)


C#




// C# program to sort an array according to count of set
// bits using Array.Sort() method
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program {
 
  // Driver code
  static void Main(string[] args) {
    int[] arr = {
      1,
      2,
      3,
      4,
      5,
      6
    };
    int n = 6;
    SortBySetBitCount(arr, n);
    PrintArr(arr, n);
    Console.WriteLine();
  }
 
  // Utility function to print an array
  private static void PrintArr(int[] arr, int n) {
    for (int i = 0; i < n; i++)
      Console.Write(arr[i] + " ");
  }
 
  // Function to sort according to bit count using std::sort
  private static void SortBySetBitCount(int[] arr, int n) {
    Array.Sort(arr, new CountComparer());
  }
 
  // custom comparator of std::sort
  private class CountComparer: IComparer < int > {
    public int Compare(int x, int y) {
      int c1 = CountBits(x);
      int c2 = CountBits(y);
      // custom comparator of std::sort
      if (c1 <= c2)
        return 1;
      else
        return -1;
    }
 
    // a utility function that returns total set bits count in an integer
    private int CountBits(int a) {
      int count = 0;
      while (a != 0) {
        if ((a & 1) == 1)
          count += 1;
        a = a >> 1;
      }
      return count;
    }
  }
}
 
// The code is contributed by Nidhi Goel.


Javascript




<script>
// Javascript program to sort an array according to
// count of set bits using std::sort()
 
function  printArr(arr,n)
{
    // TODO Auto-generated method stub
        for (let i = 0; i < n; i++)
            document.write(arr[i] + " ");
            
}
 
function sortBySetBitCount(arr,n)
{
    arr.sort(function(a,b){
        c1 = Number(a.toString(2).split("").sort().join("")).toString().length;
        c2 = Number(b.toString(2).split("").sort().join("")).toString().length;
         
        return c2-c1;
    })
}
 
let arr = [1, 2, 3, 4, 5, 6 ];
let  n = 6;
sortBySetBitCount(arr, n);
printArr(arr, n);
document.write();
 
// This code is contributed by ab2127
</script>


Output

3 5 6 1 2 4 

Auxiliary Space: O(1)
Time complexity: O(n log n)

Method 3: Counting Sort based

This problem can be solved in O(n) time. The idea is similar to counting sort.

Note: There can be a minimum 1 set-bit and only a maximum of 31set-bits in an integer.

Steps (assuming that an integer takes 32 bits):

  1. Create a vector “count” of size 32. Each cell of count i.e., count[i] is another vector that stores all the elements whose set-bit-count is i
  2. Traverse the array and do the following for each element:
    1. Count the number set-bits of this element. Let it be ‘setbitcount’
    2. count[setbitcount].push_back(element)
  3. Traverse ‘count’ in reverse fashion(as we need to sort in non-increasing order) and modify the array.

Capture

C++




// C++ program to sort an array according to
// count of set bits using std::sort()
#include <bits/stdc++.h>
using namespace std;
 
// a utility function that returns total set bits
// count in an integer
int countBits(int a)
{
    int count = 0;
    while (a)
    {
        if (a & 1 )
            count+= 1;
        a = a>>1;
    }
    return count;
}
 
// Function to sort according to bit count
// This function assumes that there are 32
// bits in an integer.
void sortBySetBitCount(int arr[],int n)
{
    vector<vector<int> > count(32);
    int setbitcount = 0;
    for (int i=0; i<n; i++)
    {
        setbitcount = countBits(arr[i]);
        count[setbitcount].push_back(arr[i]);
    }
 
    int j = 0;  // Used as an index in final sorted array
 
    // Traverse through all bit counts (Note that we
    // sort array in decreasing order)
    for (int i=31; i>=0; i--)
    {
        vector<int> v1 = count[i];
        for (int i=0; i<v1.size(); i++)
            arr[j++] = v1[i];
    }
}
 
// Utility function to print an array
void printArr(int arr[], int n)
{
    for (int i=0; i<n; i++)
        cout << arr[i] << " ";
}
 
// Driver Code
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    int n = sizeof(arr)/sizeof(arr[0]);
    sortBySetBitCount(arr, n);
    printArr(arr, n);
    return 0;
}


Java




// Java program to sort an
// array according to count
// of set bits using std::sort()
import java.util.*;
class GFG{
 
// a utility function that
// returns total set bits
// count in an integer
static int countBits(int a)
{
  int count = 0;
  while (a > 0)
  {
    if ((a & 1) > 0 )
      count += 1;
    a = a >> 1;
  }
  return count;
}
 
// Function to sort according to
// bit count. This function assumes
// that there are 32 bits in an integer.
static void sortBySetBitCount(int arr[],
                              int n)
{
  Vector<Integer> []count =
         new Vector[32];
   
  for (int i = 0;
           i < count.length; i++)
    count[i] = new Vector<Integer>();
   
  int setbitcount = 0;
   
  for (int i = 0; i < n; i++)
  {
    setbitcount = countBits(arr[i]);
    count[setbitcount].add(arr[i]);
  }
 
  // Used as an index in
  // final sorted array
  int j = 0
 
  // Traverse through all bit
  // counts (Note that we sort
  // array in decreasing order)
  for (int i = 31; i >= 0; i--)
  {
    Vector<Integer> v1 = count[i];
     
    for (int p = 0; p < v1.size(); p++)
      arr[j++] = v1.get(p);
  }
}
 
// Utility function to print
// an array
static void printArr(int arr[],
                     int n)
{
  for (int i = 0; i < n; i++)
    System.out.print(arr[i] + " ");
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {1, 2, 3, 4, 5, 6};
  int n = arr.length;
  sortBySetBitCount(arr, n);
  printArr(arr, n);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to sort an array according to
# count of set bits using std::sort()
 
# a utility function that returns total set bits
# count in an integer
def countBits(a):
    count = 0
    while (a):
        if (a & 1 ):
            count += 1
        a = a>>1
    return count
 
# Function to sort according to bit count
# This function assumes that there are 32
# bits in an integer.
def sortBySetBitCount(arr,n):
    count = [[] for i in range(32)]
    setbitcount = 0
    for i in range(n):
        setbitcount = countBits(arr[i])
        count[setbitcount].append(arr[i])
 
    j = 0 # Used as an index in final sorted array
 
    # Traverse through all bit counts (Note that we
    # sort array in decreasing order)
    for i in range(31, -1, -1):
        v1 = count[i]
        for i in range(len(v1)):
            arr[j] = v1[i]
            j += 1
 
# Utility function to print an array
def printArr(arr, n):
    print(*arr)
 
# Driver Code
arr = [1, 2, 3, 4, 5, 6]
n = len(arr)
sortBySetBitCount(arr, n)
printArr(arr, n)
 
# This code is contributed by mohit kumar 29


C#




// C# program to sort an
// array according to count
// of set bits using std::sort()
using System;
using System.Collections.Generic;
class GFG{
 
// a utility function that
// returns total set bits
// count in an integer
static int countBits(int a)
{
  int count = 0;
  while (a > 0)
  {
    if ((a & 1) > 0 )
      count += 1;
    a = a >> 1;
  }
  return count;
}
 
// Function to sort according to
// bit count. This function assumes
// that there are 32 bits in an integer.
static void sortBySetBitCount(int []arr,
                              int n)
{
  List<int> []count =
       new List<int>[32];
 
  for (int i = 0;
           i < count.Length; i++)
    count[i] = new List<int>();
 
  int setbitcount = 0;
 
  for (int i = 0; i < n; i++)
  {
    setbitcount = countBits(arr[i]);
    count[setbitcount].Add(arr[i]);
  }
 
  // Used as an index in
  // readonly sorted array
  int j = 0; 
 
  // Traverse through all bit
  // counts (Note that we sort
  // array in decreasing order)
  for (int i = 31; i >= 0; i--)
  {
    List<int> v1 = count[i];
 
    for (int p = 0; p < v1.Count; p++)
      arr[j++] = v1[p];
  }
}
 
// Utility function to print
// an array
static void printArr(int []arr,
                     int n)
{
  for (int i = 0; i < n; i++)
    Console.Write(arr[i] + " ");
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {1, 2, 3, 4, 5, 6};
  int n = arr.Length;
  sortBySetBitCount(arr, n);
  printArr(arr, n);
}
}
 
// This code is contributed by Amit Katiyar


Javascript




<script>
// Javascript program to sort an
// array according to count
// of set bits using std::sort()
 
// a utility function that
// returns total set bits
// count in an integer
function countBits(a)
{
    let count = 0;
  while (a > 0)
  {
    if ((a & 1) > 0 )
      count += 1;
    a = a >> 1;
  }
  return count;
}
 
// Function to sort according to
// bit count. This function assumes
// that there are 32 bits in an integer.
function sortBySetBitCount(arr,n)
{
let count = new Array(32);
    
  for (let i = 0;
           i < count.length; i++)
    count[i] = [];
    
  let setbitcount = 0;
    
  for (let i = 0; i < n; i++)
  {
    setbitcount = countBits(arr[i]);
    count[setbitcount].push(arr[i]);
   }
  
  // Used as an index in
  // final sorted array
  let j = 0;
  
  // Traverse through all bit
  // counts (Note that we sort
  // array in decreasing order)
  for (let i = 31; i >= 0; i--)
  {
    let v1 = count[i];
      
    for (let p = 0; p < v1.length; p++)
      arr[j++] = v1[p];
  }
}
 
// Utility function to print
// an array
function printArr(arr,n)
{
    for (let i = 0; i < n; i++)
        document.write(arr[i] + " ");
}
 
// Driver Code
let arr = [1, 2, 3, 4, 5, 6];
let n = arr.length;
sortBySetBitCount(arr, n);
printArr(arr, n);
 
// This code is contributed by patel2127
</script>


Output

3 5 6 1 2 4 

Time complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using MultiMap

Steps:

  • Create a MultiMap whose key values will be the negative of the number of set-bits of the element.
  • Traverse the array and do following for each element:
    • Count the number set-bits of this element. Let it be ‘setBitCount’
    • count.insert({(-1) * setBitCount, element})
  • Traverse ‘count’ and print the second elements.

Below is the implementation of the above approach:

C++




// C++ program to implement
// simple approach to sort
// an array according to
// count of set bits.
#include<bits/stdc++.h>
using namespace std;
 
// Function to count setbits
int setBitCount(int num){
    int count = 0;
    while ( num )
    {
        if ( num & 1)
        count++;
        num >>= 1;
    }
    return count;
}
 
// Function to sort By SetBitCount
void sortBySetBitCount(int arr[], int n)
{   
    multimap< int, int > count;
   
    // Iterate over all values and
    // insert into multimap
    for( int i = 0 ; i < n ; ++i )
    {
        count.insert({(-1) *
            setBitCount(arr[i]), arr[i]});
    }
   
    for(auto i : count)
    cout << i.second << " " ;
    cout << "\n" ;
}
 
// Driver Code
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    int n = sizeof(arr)/sizeof(arr[0]);
    sortBySetBitCount(arr, n);
}
 
// This code is contributed by Ashok Karwa


Java




// Java program to implement
// simple approach to sort
// an array according to
// count of set bits.
import java.io.*;
import java.util.*;
class GFG
{
 
  // Function to count setbits
  static int setBitCount(int num)
  {
    int count = 0;
    while ( num != 0 )
    {
      if ( (num & 1) != 0)
        count++;
      num >>= 1;
    }
    return count;
  }
 
  // Function to sort By SetBitCount
  static void sortBySetBitCount(int[] arr, int n)
  {
    ArrayList<ArrayList<Integer>> count = new ArrayList<ArrayList<Integer>>();
 
    // Iterate over all values and
    // insert into multimap
    for( int i = 0 ; i < n ; ++i )
    {
      count.add(new ArrayList<Integer>(Arrays.asList((-1) * setBitCount(arr[i]), arr[i])));
    }
 
    Collections.sort(count, new Comparator<ArrayList<Integer>>() {   
      @Override
      public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
        return o1.get(0).compareTo(o2.get(0));
      }              
    });
 
    for(int i = 0; i < count.size(); i++)
    {
      System.out.print(count.get(i).get(1) + " ");
    }
 
  }
 
  // Driver code
  public static void main (String[] args)
  {
 
    int arr[] = {1, 2, 3, 4, 5, 6};
    int n = arr.length;
    sortBySetBitCount(arr, n);
  }
}
 
// This code is contributed by avanitrachhadiya2155


Python3




# Python3 program to implement
# simple approach to sort
# an array according to
# count of set bits.
 
# Function to count setbits
def setBitCount(num):
     
    count = 0
     
    while (num):
        if (num & 1):
            count += 1
             
        num = num >> 1
         
    return count
 
# Function to sort By SetBitCount
def sortBySetBitCount(arr, n):
     
    count = []
     
    # Iterate over all values and
    # insert into multimap
    for i in range(n):
        count.append([(-1) *
        setBitCount(arr[i]), arr[i]])
         
    count.sort(key = lambda x:x[0])
     
    for i in range(len(count)):
        print(count[i][1], end = " ")
 
# Driver Code
arr = [ 1, 2, 3, 4, 5, 6 ]
n = len(arr)
 
sortBySetBitCount(arr, n)
 
# This code is contributed by rag2127


C#




// C# program to implement
// simple approach to sort
// an array according to
// count of set bits.
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to count setbits
    static int setBitCount(int num){
        int count = 0;
        while ( num != 0)
        {
            if ( (num & 1) != 0)
            count++;
            num >>= 1;
        }
        return count;
    }
     
    // Function to sort By SetBitCount
    static void sortBySetBitCount(int[] arr, int n)
    {   
        List<Tuple<int, int>> count = new List<Tuple<int, int>>(); 
        
        // Iterate over all values and
        // insert into multimap
        for( int i = 0 ; i < n ; ++i )
        {
            count.Add(new Tuple<int,int>((-1) * setBitCount(arr[i]), arr[i]));
        }
         
        count.Sort();
         
        foreach(Tuple<int, int> i in count)
        {
            Console.Write(i.Item2 + " ");
        }
        Console.WriteLine();
    }
 
  static void Main() {
    int[] arr = {1, 2, 3, 4, 5, 6};
    int n = arr.Length;
    sortBySetBitCount(arr, n);
  }
}


Javascript




<script>
// Javascript program to implement
// simple approach to sort
// an array according to
// count of set bits.
 
// Function to count setbits
function setBitCount(num) {
 
  count = 0
 
  while (num) {
    if (num & 1) {
      count += 1
    }
    num = num >> 1
  }
  return count
}
 
// Function to sort By SetBitCount
function sortBySetBitCount(arr, n) {
 
  let count = []
 
  // Iterate over all values and
  // insert into multimap
  for (let i = 0; i < n; i++) {
    count.push([(-1) * setBitCount(arr[i]), arr[i]])
  }
 
  count.sort((a, b) => a[0] - b[0])
 
  for (let i = 0; i < count.length; i++)
    document.write(count[i][1] + " ")
}
 
// Driver Code
let arr = [1, 2, 3, 4, 5, 6]
let n = arr.length
 
sortBySetBitCount(arr, n)
 
// This code is contributed by gfgking
</script>


Output

3 5 6 1 2 4 

Time complexity: O(n log n)
Auxiliary Space: O(n)



Next Article
Article Tags :
Practice Tags :

Similar Reads

Sort an array according to count of set bits | Set 2
Given an array arr[] of positive integers, the task is to sort the array in decreasing order of count of set bits in binary representations of array elements. For integers having same number of set bits in their binary representation, sort according to their position in the original array i.e., a stable sort. For example, if input array is {3, 5},
6 min read
Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X & Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X & Y) = M, where ⊕ denotes the Bitwise XOR and & denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Rank the array according to rightmost set bit and least set bits
Given an array arr[] of N integers, the task is to replace each element of Array with their rank according to Rightmost-Set Bit (RSB) in descending manner, If the RSB is the same for two numbers then choose the one which has the least number of set bits if the set bits of two numbers are same then choose the number who comes first in the array. Exa
10 min read
Flip bits of the sum of count of set bits of two given numbers
Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum. Examples: Input: A = 5, B = 7Output: 2Explanation:Binary representation of A is 101.Binary representation of B is 111.Count of set bits in A and B = 2 + 3 = 5.Binary representation of the sum obtained = 101Flipping the bits of th
5 min read
Check if bits of a number has count of consecutive set bits in increasing order
Given a integer n > 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern
11 min read
Sort an array according to the increasing count of distinct Prime Factors
Given an array of integers. The task is to sort the given array on the basis of increasing count of distinct prime factors. Examples: Input : arr[] = {30, 2, 1024, 210, 3, 6} Output : 2 1024 3 6 30 210 Input : arr[] = {12, 16, 27, 6} Output : 16 27 6 12 A naive approach is to find all the prime factors of each elements of the array and pair the cou
9 min read
Sort an array according to the increasing frequency of the digit K in the array elements
Given an array arr[] of size N, and an integer K representing a digit, the task is to print the given array in increasing order according to the increasing frequency of the digit K in the array elements. Examples: Input: arr[] = {15, 66, 26, 91}, K = 6Output: 15 91 26 66Explanation:The frequency of digit 6 in array elements is {0, 2, 1, 0}. The ele
8 min read
Sort an array according to the order defined by another array
Given two arrays arr1[] and arr2[] of size m and n, the task is to sort arr1[] such that the relative order among the elements matches the order in arr2[]. For elements not present in arr2[], append them at the end in sorted order. Example: Input: arr1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8} arr2[] = {2, 1, 8, 3}Output: arr1[] = {2, 2, 1, 1, 8, 8, 3,
14 min read
Minimize cost of swapping set bits with unset bits in a given Binary string
Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j - i). Note: A swapped bit can't be swapped twice and the count of set bit in the given binary string is at most N/2. Examples: Input: S = "1010001"Output: 3Expla
12 min read
Print numbers having first and last bits as the only set bits
Given a positive integer n. The problem is to print numbers in the range 1 to n having first and last bits as the only set bits.Examples: Input : n = 10 Output : 1 3 5 9 (1)10 = (1)2. (3)10 = (11)2. (5)10 = (101)2. (9)10 = (1001)2 Naive Approach: Print "1". Now for i = 3 to n, check if (i-1) is a Perfect power of two or not. If true then print i. C
10 min read
Python | Sort an array according to absolute difference
Given an array of N distinct elements and a number val, rearrange the array elements according to the absolute difference with val, i. e., element having minimum difference comes first and so on. Also the order of array elements should be maintained in case two or more elements have equal differences. Examples: Input: val = 6, a = [7, 12, 2, 4, 8,
3 min read
Sort an Array of Strings according to the number of Vowels in them
Given an array arr[] of N strings, the task is to sort these strings according to the numbers of vowels in them. Examples: Input: arr[] = { "geeks", "for", "coding" } Output: for, coding, geeks for -> o = 1 vowel coding -> o, i = 2 vowels geeks -> e, e = 2 vowels Input: arr[] = { "lmno", "pqrst", "aeiou", "xyz" } Output: pqrst, xyz, lmno,
10 min read
Sort an array of Strings according frequency
Given an array of strings arr[], the task is to sort the array of strings according to the frequency of each string, in ascending order. If two elements have the same frequency, then they are sorted into lexicographical order. Examples: Input: arr[] = {"Geeks", "for", "Geeks"} Output: {"for", "Geeks"} Explanation: As the string "Geeks" has a freque
8 min read
Sort integers in array according to their distance from the element K
Given an array arr[] of N integers and an integer K, the task is to sort these integers according to their distance from given integer K. If more than 1 element is at the same distance, print them in increasing order.Note: Distance between two elements in the array is measured as the difference between their index.Note: The integer K is always pres
8 min read
Sort the array according to their cubes of each element
Given an array arr[] of N integers, the task is to sort the array according to the cubes of each element. Examples: Input: arr[] = { 4, -1, 0, -5, 6 } Output: -5 -1 0 4 6 Input: arr[] = { 12, 3, 0, 11 } Output: 0 3 11 12 Approach: The idea is to use the Comparator function with an inbuilt sort function() to sort the array according to the cubes of
4 min read
Sort Array according to modulus of their values with their frequencies
Given an array arr containing N positive integers, sort them according to the increasing modulus of their values with their frequencies. Example: Input: arr[]={1, 1, 5, 3, 2, 3, 3, 3, 4, 5, 4, 5}Output: 2 4 4 1 1 5 5 5 3 3 3 3 Explanation:The elements are sorted in the following order:2 % frequency(2) = 2 % 1 = 04 % frequency(4) = 4 % 2 = 01 % freq
6 min read
Sort given Array in descending order according to highest power of prime factors
Given an array arr[] of size N. The task is to sort the elements in arr[] based to their Highest Degree of Expression, in descending order. The Highest Degree of a number is defined as the maximum value in which it can be expressed as the power of its factors. Note: If the numbers have the same degree of expression the element coming first in the o
12 min read
Sort an array according to absolute difference with given value
Given an array of N distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., an element having minimum difference comes first, and so on. Note: If two or more elements are at equal distances arrange them in the same sequence as in the given array. Examples: Input: x = 7, arr[] = {10, 5, 3, 9, 2}Ou
10 min read
Sort an array of strings according to string lengths
We are given an array of strings, we need to sort the array in increasing order of string lengths.Examples: Input : {"GeeksforGeeeks", "I", "from", "am"}Output : I am from GeeksforGeeks Input : {"You", "are", "beautiful", "looking"}Output : You are looking beautiful A simple solution is to write our own sort function that compares string lengths to
10 min read
Sort an array according to absolute difference with a given value "using constant extra space"
Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., element having minimum difference comes first and so on, using constant extra space. Note : If two or more elements are at equal distance arrange them in same sequence as in the given array.Examples: Input : arr[] = {10,
7 min read
Check if array can be sorted by swapping pairs with GCD of set bits count equal to that of the smallest array element
Given an array arr[] consisting of N integers, the task is to check if it is possible to sort the array using the following swap operations: Swapping of two numbers is valid only if the Greatest Common Divisor of count of set bits of the two numbers is equal to the number of set bits in the smallest element of the array. If it is possible to sort t
9 min read
Print elements of an array according to the order defined by another array | set 2
Given two arrays a1[] and a2[], print elements of a1 in such a way that the relative order among the elements will be the same as those are in a2. That is, elements which come before in the array a2[], print those elements first from the array a1[]. For the elements not present in a2, print them at last in sorted order. It is also given that the nu
7 min read
Toggle bits of a number except first and last bits
Given a number, the task is to toggle bits of the number except the first and the last bit.Examples: Input : 10 Output : 12 Binary representation:- 1 0 1 0 After toggling first and last : 1 1 0 0 Input : 9 Output : 15 Binary representation : 1 0 0 1 After toggling first and last : 1 1 1 1 Prerequisite: Find most significant set bit of a number Gene
8 min read
Check if all bits can be made same by flipping two consecutive bits
Given a binary string, the task is to find whether all the digits of the string can be made equal i.e either 0 or 1 by flipping two consecutive bits any number of times.Examples: Input: 01011Output: YESExplanation:Flip 2nd and 3rd bit -> 00111, again flipping 1'st and 2'nd bit -> 11111 Input: 100011Output: NOExplanation:No number of moves can
5 min read
Count positions in Binary Matrix having equal count of set bits in corresponding row and column
Given a boolean matrix mat[][] of size M * N, the task is to print the count of indices from the matrix whose corresponding row and column contain an equal number of set bits. Examples: Input; mat[][] = {{0, 1}, {1, 1}}Output: 2Explanation:Position (0, 0) contains 1 set bit in corresponding row {(0, 0), (0, 1)} and column {(0, 0), (1, 0)}.Position
10 min read
Python | Sort a List according to the Length of the Elements
In this program, we need to accept a list and sort it based on the length of the elements present within. Examples: Input : list = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"] Output : ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad'] Input : list = [["ram", "mohan", "aman"], ["gaurav"], ["amy", "sima", "a
4 min read
Sort the numbers according to their product of digits
Given an array arr[] of N non-negative integers, the task is to sort these integers according to the product of their digits.Examples: Input: arr[] = {12, 10, 102, 31, 15} Output: 10 102 12 31 15 10 -> 1 * 0 = 0 102 -> 1 * 0 * 2 = 0 12 -> 1 * 2 = 2 31 -> 3 * 1 = 3 15 -> 1 * 5 = 5Input: arr[] = {12, 10} Output: 10 12 Approach: The ide
6 min read
Sort a string according to the frequency of characters
Given a string str, the task is to sort the string according to the frequency of each character, in ascending order. If two elements have the same frequency, then they are sorted in lexicographical order.Examples: Input: str = "geeksforgeeks" Output: forggkksseeee Explanation: Frequency of characters: g2 e4 k2 s2 f1 o1 r1 Sorted characters accordin
15 min read
Sort a string according to the order defined by another string
Given two strings (of lowercase letters), a pattern, and a string. The task is to sort strings according to the order defined by the pattern. It may be assumed that the pattern has all characters of the string and all characters in the pattern appear only once. Examples: Input : pat = "bca", str = "abc" Output : str = "bca" Input : pat = "bxyzca",
10 min read
Sort the numbers according to their sum of digits
Given an array arr[] of N non-negative integers, the task is to sort these integers according to sum of their digits. Examples: Input: arr[] = {12, 10, 102, 31, 15} Output: 10 12 102 31 15 Explanation: 10 => 1 + 0 = 1 12 => 1 + 2 = 3 102 => 1 + 0 + 2 = 3 31 => 3 + 1= 4 15 => 1 + 5 = 6 Input: arr[] = {14, 1101, 10, 35, 0} Output: 0 10
8 min read
  翻译: