Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

后端 未结 30 2057
栀梦
栀梦 2020-12-22 14:33

I have a computer with 1 MB of RAM and no other local storage. I must use it to accept 1 million 8-digit decimal numbers over a TCP connection, sort them, and then send the

30条回答
  •  半阙折子戏
    2020-12-22 14:51

    While receiving the stream do these steps.

    1st set some reasonable chunk size

    Pseudo Code idea:

    1. The first step would be to find all the duplicates and stick them in a dictionary with its count and remove them.
    2. The third step would be to place number that exist in sequence of their algorithmic steps and place them in counters special dictionaries with the first number and their step like n, n+1..., n+2, 2n, 2n+1, 2n+2...
    3. Begin to compress in chunks some reasonable ranges of number like every 1000 or ever 10000 the remaining numbers that appear less often to repeat.
    4. Uncompress that range if a number is found and add it to the range and leave it uncompressed for a while longer.
    5. Otherwise just add that number to a byte[chunkSize]

    Continue the first 4 steps while receiving the stream. The final step would be to either fail if you exceeded memory or start outputting the result once all the data is collected by beginning to sort the ranges and spit out the results in order and uncompressing those in order that need to be uncompressed and sort them when you get to them.

提交回复
热议问题