For a 2-way merge sort for a table with n records, the entire merge sort needs to be performed log2 n times (passes), and a total of n*log2 n records are moved. A specific explanation for this sentence.

Disclaimer: There may be deficiencies in this article. If there are any mistakes, please correct me and communicate politely. Thank you very much.

Convention: log2 n represents the base 2, the logarithm of n

1. Why do you need to perform log2 n times?

It can be understood in this way: Two-way merging is to combine two-way data into one. Looking at it conversely, it is to divide n data by 2 and round until n becomes 1, so log2 n times are required.

If you understand it from the perspective of merge trees, it will be a little troublesome. (Look carefully at the merge tree above. The number of trips (layers - 1) that need to be performed is the height of the merge tree minus one. Note that one must be reduced to conform to the next logic. Assuming that there are n records and a total of k layers, then 2 ^(k-1) >= n. So k-1>=log2 n, roughly estimated to be log2 n.)

2. Why do you need to move nlog2n records?

 Take a closer look at the above figure, the merge sort is to compare the size of the elements pointed to by i and j, and select the smaller one to store in the position pointed to by k. Every time a data is stored in k, we say that a record movement has occurred. So each trip will happen n times the movement of records. A total of log2 n times, so a total of n*log2 n records will be moved.

Written at the end: The relevant pictures are from a computer postgraduate entrance examination institution

Guess you like

Origin blog.csdn.net/fly_view/article/details/127754088