4

How we can prove that $2n−1$ comparisons are sometimes necessary to correctly merge two sorted sequences of $n$ elements each into one sorted sequence? I tried to prove it with binary decision tree, but it was not working.

SilvioM
  • 843
  • 3
  • 13

1 Answers1

1

Let the sequences be $A_{1..n}$ and $B_{1..n}$, merging takes $2n - 1$ comparisons if $A_1 < B_1 < A_2 < B_2 < A_3 < B_3 < \cdots < A_n < B_n$.

It compares $A_1$ with $B_1$, $A_2$ with $B_1$, $A_2$ with $B_2$, $A_3$ with $B_2$, $A_3$ with $B_3$, to $A_n$ with $B_n$.

It is identical to $A_1$ with $B_1$, $B_1$ with $A_2$, $A_2$ with $B_2$, $B_2$ with $A_3$, $A_3$ with $B_3$, to $A_n$ with $B_n$.

It requires each $A_i$ and $B_j$ comparison above be made to distinguish $A_i < B_j$ and $A_i > B_j$.

It resembles the original condition, so there are $2n$ elements linked by $2n - 1$ inequalities.

Kenneth Kho
  • 654
  • 2
  • 17
  • 4
    This doesn't prove that $2n - 1$ comparisons are necessary, just that this particular method of merging uses that many. – orlp Mar 04 '24 at 14:10
  • 2
    No, because for it to be necessary you must prove there doesn't exist some other algorithm that could do better. – orlp Mar 04 '24 at 14:31
  • It is not unknown, see the answer of the linked duplicate question, which refers to Theorem M in Chapter 5.3.2 of Volume 3 of the TAOCP by Knuth. – orlp Mar 04 '24 at 14:44
  • It is definitely similar, but you need to argue that this holds regardless of algorithm. You have the right idea but need to argue from the opposite direction: that you need to compare $A_1$ with $B_1$, for example. – orlp Mar 04 '24 at 17:07
  • Take any B_k. You must compare it to A_k and A_k+1, otherwise an array with A_k > B_k or A_k+1 < B_k would not be sorted correctly. That’s true for all k except k=n-1 where A_k+1 does not exist, so 2n-1 comparisons are needed. Other arrays may need fewer comparisons. – gnasher729 Mar 05 '24 at 07:23
  • @orlp I added the fourth line, the proof is now clearly sufficient. But is the fourth line necessary? Isn't this method of merging guaranteed to produce the least number of comparison? We could use bogo sort to merge, but it is not necessary to perform that many comparisons. – Kenneth Kho Mar 08 '24 at 14:09