📌  相关文章
📜  根据设置的位数对数组进行排序套装2

📅  最后修改于: 2021-05-25 06:10:52             🧑  作者: Mango

给定一个正整数的数组arr [] ,任务是按照数组元素的二进制表示形式按设置位的计数从高到低的顺序对数组进行排序。
对于在二进制表示形式中具有相同数目的置位位数的整数,请根据其在原始数组中的位置进行排序,即稳定排序。例如,如果输入数组为{3,5},则输出数组也应为{3,5}。请注意,3和5具有相同的编号设置位。

例子:

方法:我们已经在上一节中讨论了使用各种方法基于设置的位数进行排序的方法。这篇文章包含使用地图的实现。
众所周知,地图/多图以排序方式存储数据。因此,如果我们在映射中为arr [i]存储(32 – countsetbits(arr [i])),则输出将以设置位计数的降序出现,这是所需的输出。

下面是上述方法的实现:

C/C++
// C++ implementation of the approach
#include 
using namespace std;
  
// function to sort the array according
// to the number of set bits in elements
void sortArr(int arr[], int n)
{
    multimap map;
  
    for (int i = 0; i < n; i++) {
        int count = 0;
        int k = arr[i];
  
        // Counting no of setBits in arr[i]
        while (k) {
            k = k & k - 1;
            count++;
        }
  
        // The count is subtracted from 32
        // because the result needs
        // to be in descending order
        map.insert(make_pair(32 - count, arr[i]));
    }
  
    // Printing the numbers in descending
    // order of set bit count
    for (auto it = map.begin(); it != map.end(); it++) {
        cout << (*it).second << " ";
    }
}
  
// Driver code
int main()
{
    int arr[] = { 5, 2, 3, 9, 4, 6, 7, 15, 32 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    sortArr(arr, n);
  
    return 0;
}


Python3
# Python3 implementation of the approach
  
# function to sort the array according
# to the number of set bits in elements
def sortArr(arr, n):
  
    mp = []
  
    for i in range( n):
        count = 0
        k = arr[i]
  
        # Counting no of setBits in arr[i]
        while (k):
            k = k & k - 1
            count += 1
          
        # The count is subtracted from 32
        # because the result needs
        # to be in descending order
        mp.append((32 - count, arr[i]))
  
    # Printing the numbers in descending
    # order of set bit count
    mp.sort(key = lambda x: x[0]) 
    for it in mp:
        print(it[1], end= " ")
  
# Driver code
if __name__ == "__main__":
      
    arr = [ 5, 2, 3, 9, 4, 6, 7, 15, 32 ]
    n = len(arr)
  
    sortArr(arr, n)
  
# This code is contributed by chitranayal


输出:
15 7 5 3 9 6 2 4 32