How can I sort numbers lexicographically?

前端 未结 14 917
半阙折子戏
半阙折子戏 2020-12-09 04:56

Here is the scenario.

I am given an array \'A\' of integers. The size of the array is not fixed. The function that I am supposed to write may be called once with an

14条回答
  •  失恋的感觉
    2020-12-09 05:36

    If you want to try a better preprocess-sort-postprocess, then note that an int is at most 10 decimal digits (ignoring signed-ness for the time being).

    So the binary-coded-decimal data for it fits in 64 bits. Map digit 0->1, 1->2 etc, and use 0 as a NUL terminator (to ensure that "1" comes out less than "10"). Shift each digit in turn, starting with the smallest, into the top of a long. Sort the longs, which will come out in lexicographical order for the original ints. Then convert back by shifting digits one at a time back out of the top of each long:

    uint64_t munge(uint32_t i) {
        uint64_t acc = 0;
        while (i > 0) {
            acc = acc >> 4;
            uint64_t digit = (i % 10) + 1;
            acc += (digit << 60);
            i /= 10;
        }
        return acc;
    }
    
    uint32_t demunge(uint64_t l) {
        uint32_t acc = 0;
        while (l > 0) {
            acc *= 10;
            uint32_t digit = (l >> 60) - 1;
            acc += digit;
            l << 4;
        }
    }
    

    Or something like that. Since Java doesn't have unsigned ints, you'd have to modify it a little. It uses a lot of working memory (twice the size of the input), but that's still less than your initial approach. It might be faster than converting to strings on the fly in the comparator, but it uses more peak memory. Depending on the GC, it might churn its way through less memory total, though, and require less collection.

提交回复
热议问题