fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // function to sort the array according
  5. // to the number of set bits in elements
  6. void sortArr(long long int arr[], long long int n)
  7. {
  8. multimap<long long int, long long int> map;
  9.  
  10. for (long long int i = 0; i < n; i++) {
  11. long long int count = 0;
  12. long long int k = arr[i];
  13.  
  14. // Counting no of setBits in arr[i]
  15. while (k) {
  16. k = k & k - 1;
  17. count++;
  18. }
  19.  
  20. // The count is subtracted from 32
  21. // because the result needs
  22. // to be in descending order
  23. map.insert(make_pair(count, arr[i]));
  24. }
  25.  
  26. // Printing the numbers in descending
  27. // order of set bit count
  28. for (auto it = map.begin(); it != map.end(); it++) {
  29. cout << (*it).second << " ";
  30. }
  31. }
  32.  
  33. // Driver code
  34. int main()
  35. {
  36. long long int arr[] = { 5, 4, 3, 9, 2, 6, 7, 15, 32 };
  37. long long int n = sizeof(arr) / sizeof(arr[0]);
  38. sort(arr,arr+n);
  39. sortArr(arr, n);
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0s 4288KB
stdin
Standard input is empty
stdout
2 4 32 3 5 6 9 7 15