Professional Documents
Culture Documents
Conquer
Counting
Design and Analysis
Inversions II
of Algorithms I
Piggybacking on Merge Sort
Tim Roughgarden
High-Level Algorithm (revised)
Tim Roughgarden
Pseudocode for Merge:
D = output [length = n] for k = 1 to n
B = 1st sorted array [n/2] if B(i) < C(j)
C = 2nd sorted array [n/2] D(k) = B(i)
i=1 i++
j=1 else [C(j) < B(i)]
D(k) = C(j)
j++
end (ignores end cases)
Tim Roughgarden
Suppose the input array A has no split inversions. What is the
relationship between the sorted subarrays B and C?
B has the smallest element of A, C the second-smallest, B, the third-
smallest, and so on.
All elements of B are less than all elements of C.
Tim Roughgarden
General Claim
Tim Roughgarden
Merge_and_CountSplitInv
Tim Roughgarden