Merge
Merge
4.1 4.3
4.2 4.4
Abstract inplace merge Mergesort example
4.6 4.8
Recurrences Mergesort and numbers
Direct relationship to recursive programs THM: Number of compares used by Mergesort for
(most programs are "recursive") is the same as
number of bits in the binary representations
Easy telescoping recurrences of all the numbers less than N (plus N-1).
T(N) = T(N-1) + 1 T(N) = N
T(2^n) = T(2^(n-1)) + 1 T(N) = lg N if N=2^n Proof: They satisfy the same recurrence
C(2N) = C(N) + C(N) + 2N
Short list of important recurrences C(2N+1) = C(N) + C(N+1) + 2N+1
T(N) = T(N/2) + 1 T(N) = lg N
T(N) = T(N/2) + N T(N) = N 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1
T(N) = 2T(N/2) + 1 T(N) = N 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0
T(N) = 2T(N/2) + N T(N) = N lg N 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1
Details in Chapter 2 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
4.9 4.11
THM: Mergesort uses N lg N comparisons Divide-and-conquer algs exhibit erratic periodic behavior
T(2^n)/2^n = n
Therefore, 54
T(N) = N lg N
27
0
-18
-36
Exact for powers of two, approximate otherwise
-72
32 64 128 256 512
4.10 4.12
Guaranteed worst-case bound
Divide-and-conquer Complexity of sorting
4.13 4.15
1<3? 1<4?
Machine model: count fundamental operations
2<3? 3<4?
CODE OPTIMIZATION: Improve performance by tuning code void mergesort(Item a[], int l, int r)
concentrate on inner loop { int i, m;
for (m = 1; m < r-l; m = m+m)
For mergesort, for (i = l; i <= r-m; i += m+m)
Avoid move with recursive argument switch merge(a, i, i+m-1, min(i+m+m-1, r));
Avoid sentinels with "up-down" trick }
Combine the two? Doable, but mindbending Different set of merges than for top-down
unless N is a power of two
Can make mergesort almost as fast as quicksort
mergesort inner loop: compare, store, two incs
quicksort inner loop: compare, inc 21
16 5
8 8 5
4 4 4 4 4 1
2 2 2 2 2 2 2 2 2 2 1
4.18 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4.20
Merging linked lists Bottom-up list mergesort
link mergesort(link c)
{ link a, b;
if (c->next == NULL) return c;
a = c; b = c->next;
while ((b != NULL) && (b->next != NULL))
{ c = c->next; b = b->next->next; }
b = c->next; c->next = NULL;
return merge(mergesort(a), mergesort(b));
}
4.22