How external merge sort algorithm works?

前端 未结 5 1916
天涯浪人
天涯浪人 2020-12-07 09:52

I\'m trying to understand how external merge sort algorithm works (I saw some answers for same question, but didn\'t find what I need). I\'m reading the book \"Analysis Of A

5条回答
  •  醉话见心
    2020-12-07 10:19

    First of all, by sorting the numbers in parts of 4 numbers, you should get 3 chunks.

    A:[1,2,3,5]  
    B:[4,6,8,9]
    C:[7]
    

    Then you will read half of each file (ignore C since it won't fit) and merge them. So, you will load into memory {[1, 2], [4, 6]}. You will do a casual merge and write the result in a new chunk D:

    Compare 1 and 4 -> D:[1]
    Compare 2 and 4 -> D:[1, 2]
    

    Now the part of A that was in RAM finished merging, so now you will have to bring the second half of it in memory. Now your memory will have {[3, 5], [4, 6]}.

    Compare 3 and 4 -> D:[1, 2, 3]
    Compare 5 and 4 -> D:[1, 2, 3, 4]
    Compare 5 and 6 -> D:[1, 2, 3, 4, 5]
    

    All of chunk A got merged, so now just append the rest of B into D

    D:[1,2,3,4,5,6,8,9]
    

    Now you would have to do the same process with chunks C and D. Remember that C could have more than one number in another example. By mergind C and D you will get a new chunk E that will be the final sorted file.

    Also, note that in a bigger example you might need more merge phases. For example, if you had 20 numbers to sort, You would create 5 chunks of 4 numbers, and then you would combine and merge two of them each time, resulting in 2 chunks of 8 numbers (plus one extra of 4 numbers), and then merge the newer chunks into one of 16 numbers and so on.

提交回复
热议问题