Sorting Integers by 1 Bits and Value

Day 11/30 – LeetCode streak Today’s problem: Sort Integers by The Number of 1 Bits You have to sort an array by popcount first (fewer 1s come earlier), and if two numbers have the same count, sort them by their actual value. Instead of using 'Arrays.sort' with a comparator, I tried writing the sort logic myself with insertion sort: - For each element, treat it as 'key' and move larger elements (based on custom “bit count, then value” order) one step to the right. - 'Swap(a, b)' returns true if 'a' should come after 'b' in the final order, using a manual 'countBits' function to compare the number of 1s. - If bit counts differ, the one with more 1s is considered “greater”; if they’re equal, compare the raw integers. Day 11 takeaway: This was a nice chance to practice writing a custom sort order from scratch—once the comparison rule is clear (“by 1-bits, then by value”), the rest is just plugging that into any sorting algorithm. #leetcode #dsa #java #bitmanipulation #sorting

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories