Sort Integers by The Number of 1 Bits

easy array bit manipulation sorting

Problem

Sort the array in ascending order by the number of 1's in their binary representation. If two numbers have the same count of 1's, sort them by value (ascending).

Inputarr = [0,1,2,3,4,5,6,7,8]
Output[0,1,2,4,8,3,5,6,7]
popcount: 0→0, 1,2,4,8→1, 3,5,6→2, 7→3.

def sort_by_bits(arr):
    return sorted(arr, key=lambda x: (bin(x).count('1'), x))
function sortByBits(arr) {
  function pop(x) { let c = 0; while (x) { c += x & 1; x >>>= 1; } return c; }
  return arr.slice().sort((a, b) => pop(a) - pop(b) || a - b);
}
class Solution {
    public int[] sortByBits(int[] arr) {
        Integer[] a = new Integer[arr.length];
        for (int i = 0; i < arr.length; i++) a[i] = arr[i];
        Arrays.sort(a, (x, y) -> {
            int d = Integer.bitCount(x) - Integer.bitCount(y);
            return d != 0 ? d : x - y;
        });
        int[] r = new int[arr.length];
        for (int i = 0; i < arr.length; i++) r[i] = a[i];
        return r;
    }
}
vector sortByBits(vector arr) {
    sort(arr.begin(), arr.end(), [](int a, int b) {
        int pa = __builtin_popcount(a), pb = __builtin_popcount(b);
        return pa != pb ? pa < pb : a < b;
    });
    return arr;
}
Time: O(n log n) Space: O(n)