I'll prove that the total number of comparisons made by MergeSort when sorting an array of size n=2k is C(n)=nlog2n−n+1.
Let's start by analyzing how MergeSort works and count the comparisons:
- For an array of size n, MergeSort divides it into two subarrays of size n/2
- It recursively sorts each subarray
- It merges the two sorted subarrays, which requires comparisons
Let C(n) be the number of comparisons needed to sort an array of size n.
For the merge step, when combining two sorted arrays of size n/2, we need at most (n/2)+(n/2)−1=n−1 comparisons in the worst case.
This gives us the recurrence relation:
C(n)=2C(n/2)+(n−1)
For the base case, C(1)=0 since an array of size 1 is already sorted and requires no comparisons.
Now let's solve this recurrence relation:
C(n)=2C(n/2)+(n−1)
Substituting n=2k:
C(2k)=
Let's expand this recursively:
C(2k)=2C(2k−1)+(2
Continuing this pattern:
C(2k)=23C(2k
Since C(20)=C(1)=0, we get:
C(
Substituting back n=2k and k=log2n:
Therefore, the total number of comparisons made by MergeSort when sorting an array of size n=2k is C(n)=nlog2.