35
3
Goal
Write a function or program sort an array of integers in descending order by the number of 1's present in their binary representation. No secondary sort condition is necessary.
Example sorted list
(using 16-bit integers)
Dec Bin 1's
16375 0011111111110111 13
15342 0011101111101110 11
32425 0111111010101001 10
11746 0010110111100010 8
28436 0000110111110100 8
19944 0100110111101000 8
28943 0000011100011111 8
3944 0000011111101000 7
15752 0011110110001000 7
825 0000000011111001 6
21826 0101010101000010 6
Input
An array of 32-bit integers.
Output
An array of the same integers sorted as described.
Scoring
This is code golf for the least number of bytes to be selected in one week's time.
formatted test cases please? – FantaC – 2018-02-20T19:48:22.343
2You didn't explicitly mention, but does it need to be in descending order? – Nick T – 2014-02-19T04:12:55.530
3You're right, I missed that. Everyone else has gone with descending, so we'll stick with that. – Hand-E-Food – 2014-02-19T07:19:00.597
I think the final number (21826) has been converted wrong. according to my Windows calculator, it's 0101 0101 0100 0010, not 0010 1010 1100 0010. – Nzall – 2014-02-19T09:04:08.353
Thanks for those corrections. That's weird about 21826 because I used Excel to convert the numbers to binary. I wonder about the rest now. – Hand-E-Food – 2014-02-19T22:02:01.733
Solution using assembly and popcount instruction? – eiennohito – 2014-02-20T05:57:49.730
Some CPUs have efficient opcodes for doing this, but I suspect assembly language to be a bit too verbose to win code golf. (I think Motorola 68040 had it.) – hippietrail – 2014-02-20T07:45:35.687
Does the sort have to be stable or not? – Tim Seguine – 2014-02-24T19:57:47.017
Am I allowed to sort the input array in-place? It is a difference of 8 characters for my solution. – Tim Seguine – 2014-02-24T20:28:31.947
Stability is not required. I never said the input had to remain unchanged, so in-place sorting is fine. – Hand-E-Food – 2014-02-25T01:49:59.137