




























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























The divide-and-conquer strategy solves a problem by:
The real work is done piecemeal, in three different places: in the partitioning of problems into subproblems; at the very tail end of the recursion, when the subproblems are so small that they are solved outright; and in the gluing together of partial answers. These are held together and coordinated by the algorithm’s core recursive structure. As an introductory example, we’ll see how this technique yields a new algorithm for multi- plying numbers, one that is much more efficient than the method we all learned in elementary school!
The mathematician Carl Friedrich Gauss (1777–1855) once noticed that although the product of two complex numbers
(a + bi)(c + di) = ac − bd + (bc + ad)i
seems to involve four real-number multiplications, it can in fact be done with just three : ac, bd, and (a + b)(c + d), since
bc + ad = (a + b)(c + d) − ac − bd.
In our big-O way of thinking, reducing the number of multiplications from four to three seems wasted ingenuity. But this modest improvement becomes very significant when applied recur- sively.
55
56 Algorithms
Let’s move away from complex numbers and see how this helps with regular multiplica- tion. Suppose x and y are two n-bit integers, and assume for convenience that n is a power of 2 (the more general case is hardly any different). As a first step toward multiplying x and y, split each of them into their left and right halves, which are n/ 2 bits long:
x = x L x R = 2n/^2 x L + x R y = y L y R = 2n/^2 y L + y R.
For instance, if x = 10110110 2 (the subscript 2 means “binary”) then x L = 1011 2 , x R = 0110 2 , and x = 1011 2 × 24 + 0110 2. The product of x and y can then be rewritten as
xy = (2n/^2 x L + x R )(2n/^2 y L + y R ) = 2n^ x L y L + 2n/^2 (x L y R + x R y L ) + x R y R.
We will compute xy via the expression on the right. The additions take linear time, as do the multiplications by powers of 2 (which are merely left-shifts). The significant operations are the four n/ 2 -bit multiplications, x L y L , x L y R , x R y L , x R y R ; these we can handle by four recursive calls. Thus our method for multiplying n-bit numbers starts by making recursive calls to multiply these four pairs of n/ 2 -bit numbers (four subproblems of half the size), and then evaluates the preceding expression in O(n) time. Writing T (n) for the overall running time on n-bit inputs, we get the recurrence relation
T (n) = 4T (n/2) + O(n).
We will soon see general strategies for solving such equations. In the meantime, this particu- lar one works out to O(n^2 ), the same running time as the traditional grade-school multiplica- tion technique. So we have a radically new algorithm, but we haven’t yet made any progress in efficiency. How can our method be sped up? This is where Gauss’s trick comes to mind. Although the expression for xy seems to de- mand four n/ 2 -bit multiplications, as before just three will do: x L y L , x R y R , and (x L +x R )(y L +y R ), since x L y R +x R y L = (x L +x R )(y L +y R )−x L y L −x R y R. The resulting algorithm, shown in Figure 2.1, has an improved running time of^1
T (n) = 3T (n/2) + O(n).
The point is that now the constant factor improvement, from 4 to 3, occurs at every level of the recursion , and this compounding effect leads to a dramatically lower time bound of O(n^1.^59 ).
This running time can be derived by looking at the algorithm’s pattern of recursive calls, which form a tree structure, as in Figure 2.2. Let’s try to understand the shape of this tree. At each successive level of recursion the subproblems get halved in size. At the (log 2 n)th^ level,
(^1) Actually, the recurrence should read
T (n) ≤ 3 T (n/2 + 1) + O(n)
since the numbers (x L + x R ) and (y L + y R ) could be n/2 + 1 bits long. The one we’re using is simpler to deal with and can be seen to imply exactly the same big-O running time.
58 Algorithms
Figure 2.2 Divide-and-conquer integer multiplication. (a) Each problem is divided into three subproblems. (b) The levels of recursion.
(a)
10110010 × 01100011
(b)
2
1 1 1
2
1 1 1
2
1 1 1
2
1 1 1
Size n
Size n/ 2
log n levels Size n/ 4
Divide-and-conquer algorithms often follow a generic pattern: they tackle a problem of size n by recursively solving, say, a subproblems of size n/b and then combining these answers in O(nd) time, for some a, b, d > 0 (in the multiplication algorithm, a = 3, b = 2, and d = 1). Their running time can therefore be captured by the equation T (n) = aT (dn/be) + O(nd). We next derive a closed-form solution to this general recurrence so that we no longer have to solve it explicitly in each new instance.
Master theorem^2 If T (n) = aT (dn/be) + O(nd) for some constants a > 0 , b > 1 , and d ≥ 0 ,
(^2) There are even more general results of this type, but we will not be needing them.
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 59
Figure 2.3 Each problem of size n is divided into a subproblems of size n/b.
Size 1
Size n/b^2
Size n/b
Size n
Depth logb n
Width alogb^ n^ = nlogb^ a
Branching factor a
then
T (n) =
O(nd) if d > logb a O(nd^ log n) if d = logb a O(nlogb^ a) if d < logb a.
This single theorem tells us the running times of most of the divide-and-conquer procedures we are likely to use. Proof. To prove the claim, let’s start by assuming for the sake of convenience that n is a power of b. This will not influence the final bound in any important way—after all, n is at most a multiplicative factor of b away from some power of b (Exercise 2.2)—and it will allow us to ignore the rounding effect in dn/be. Next, notice that the size of the subproblems decreases by a factor of b with each level of recursion, and therefore reaches the base case after logb n levels. This is the height of the recursion tree. Its branching factor is a, so the kth level of the tree is made up of ak subproblems, each of size n/bk^ (Figure 2.3). The total work done at this level is
ak^ × O
( (^) n bk
)d = O(nd) ×
( (^) a bd
)k .
As k goes from 0 (the root) to logb n (the leaves), these numbers form a geometric series with
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 61
Figure 2.4 The sequence of merge operations in mergesort.
Input: 10 2 5 3 7 13 1 6
function merge(x[1... k], y[1... l]) if k = 0: return y[1... l] if l = 0: return x[1... k] if x[1] ≤ y[1]: return x[1] ◦ merge(x[2... k], y[1... l]) else: return y[1] ◦ merge(x[1... k], y[2... l])
Here ◦ denotes concatenation. This merge procedure does a constant amount of work per recursive call (provided the required array space is allocated in advance), for a total running time of O(k + l). Thus merge’s are linear, and the overall time taken by mergesort is
T (n) = 2 T (n/2) + O(n),
or O(n log n).
Looking back at the mergesort algorithm, we see that all the real work is done in merg- ing, which doesn’t start until the recursion gets down to singleton arrays. The singletons are merged in pairs, to yield arrays with two elements. Then pairs of these 2-tuples are merged, producing 4-tuples, and so on. Figure 2.4 shows an example. This viewpoint also suggests how mergesort might be made iterative. At any given mo- ment, there is a set of “active” arrays—initially, the singletons—which are merged in pairs to give the next batch of active arrays. These arrays can be organized in a queue, and processed by repeatedly removing two arrays from the front of the queue, merging them, and putting the result at the end of the queue.
62 Algorithms
In the following pseudocode, the primitive operation inject adds an element to the end of the queue while eject removes and returns the element at the front of the queue.
function iterative-mergesort(a[1... n]) Input: elements a 1 , a 2 ,... , an to be sorted
Q = [ ] (empty queue) for i = 1 to n: inject(Q, [ai]) while |Q| > 1 : inject(Q, merge(eject(Q), eject(Q))) return eject(Q)
64 Algorithms
The median of a list of numbers is its 50 th percentile: half the numbers are bigger than it, and half are smaller. For instance, the median of [45, 1 , 10 , 30 , 25] is 25 , since this is the middle element when the numbers are arranged in order. If the list has even length, there are two choices for what the middle element could be, in which case we pick the smaller of the two, say. The purpose of the median is to summarize a set of numbers by a single, typical value. The mean , or average, is also very commonly used for this, but the median is in a sense more typical of the data: it is always one of the data values, unlike the mean, and it is less sensitive to outliers. For instance, the median of a list of a hundred 1 ’s is (rightly) 1 , as is the mean. However, if just one of these numbers gets accidentally corrupted to 10 , 000 , the mean shoots up above 100 , while the median is unaffected. Computing the median of n numbers is easy: just sort them. The drawback is that this takes O(n log n) time, whereas we would ideally like something linear. We have reason to be hopeful, because sorting is doing far more work than we really need—we just want the middle element and don’t care about the relative ordering of the rest of them. When looking for a recursive solution, it is paradoxically often easier to work with a more general version of the problem—for the simple reason that this gives a more powerful step to recurse upon. In our case, the generalization we will consider is selection.
SELECTION Input: A list of numbers S; an integer k Output: The kth smallest element of S
For instance, if k = 1, the minimum of S is sought, whereas if k = b|S|/ 2 c, it is the median.
A randomized divide-and-conquer algorithm for selection
Here’s a divide-and-conquer approach to selection. For any number v, imagine splitting list S into three categories: elements smaller than v, those equal to v (there might be duplicates), and those greater than v. Call these SL, Sv, and SR respectively. For instance, if the array
S : 2 36 5 21 8 13 11 20 5 4 1
is split on v = 5, the three subarrays generated are
SL : 2 4 1 Sv : 5 5 SR : 36 21 8 13 11 20
The search can instantly be narrowed down to one of these sublists. If we want, say, the eighth -smallest element of S, we know it must be the third -smallest element of SR since |SL| + |Sv | = 5. That is, selection(S, 8) = selection(SR, 3). More generally, by checking k against the sizes of the subarrays, we can quickly determine which of them holds the desired element:
selection(S, k) =
selection(SL, k) if k ≤ |SL| v if |SL| < k ≤ |SL| + |Sv | selection(SR, k − |SL| − |Sv |) if k > |SL| + |Sv|.
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 65
The three sublists SL, Sv , and SR can be computed from S in linear time; in fact, this compu- tation can even be done in place , that is, without allocating new memory (Exercise 2.15). We then recurse on the appropriate sublist. The effect of the split is thus to shrink the number of elements from |S| to at most max{|SL|, |SR|}. Our divide-and-conquer algorithm for selection is now fully specified, except for the crucial detail of how to choose v. It should be picked quickly, and it should shrink the array substan- tially, the ideal situation being |SL|, |SR| ≈ 12 |S|. If we could always guarantee this situation, we would get a running time of
T (n) = T (n/2) + O(n),
which is linear as desired. But this requires picking v to be the median, which is our ultimate goal! Instead, we follow a much simpler alternative: we pick v randomly from S.
Efficiency analysis
Naturally, the running time of our algorithm depends on the random choices of v. It is possible that due to persistent bad luck we keep picking v to be the largest element of the array (or the smallest element), and thereby shrink the array by only one element each time. In the earlier example, we might first pick v = 36, then v = 21, and so on. This worst-case scenario would force our selection algorithm to perform
n + (n − 1) + (n − 2) + · · · +
n 2 = Θ(n^2 )
operations (when computing the median), but it is extremely unlikely to occur. Equally un- likely is the best possible case we discussed before, in which each randomly chosen v just happens to split the array perfectly in half, resulting in a running time of O(n). Where, in this spectrum from O(n) to Θ(n^2 ), does the average running time lie? Fortunately, it lies very close to the best-case time.
To distinguish between lucky and unlucky choices of v, we will call v good if it lies within the 25 th to 75 th percentile of the array that it is chosen from. We like these choices of v because they ensure that the sublists SL and SR have size at most three-fourths that of S (do you see why?), so that the array shrinks substantially. Fortunately, good v’s are abundant: half the elements of any list must fall between the 25 th to 75 th percentile! Given that a randomly chosen v has a 50% chance of being good, how many v’s do we need to pick on average before getting a good one? Here’s a more familiar reformulation (see also Exercise 1.34):
Lemma On average a fair coin needs to be tossed two times before a “heads” is seen.
Proof. Let E be the expected number of tosses before a heads is seen. We certainly need at least one toss, and if it’s heads, we’re done. If it’s tails (which occurs with probability 1 / 2 ), we need to repeat. Hence E = 1 + 12 E, which works out to E = 2.
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 67
In general, XY is not the same as Y X; matrix multiplication is not commutative. The preceding formula implies an O(n^3 ) algorithm for matrix multiplication: there are n^2 entries to be computed, and each takes O(n) time. For quite a while, this was widely believed to be the best running time possible, and it was even proved that in certain models of com- putation no algorithm could do better. It was therefore a source of great excitement when in 1969, the German mathematician Volker Strassen announced a significantly more efficient algorithm, based upon divide-and-conquer.
Matrix multiplication is particularly easy to break into subproblems, because it can be performed blockwise. To see what this means, carve X into four n/ 2 × n/ 2 blocks, and also Y :
X =
Then their product can be expressed in terms of these blocks and is exactly as if the blocks were single elements (Exercise 2.11).
XY =
We now have a divide-and-conquer strategy: to compute the size-n product XY , recursively compute eight size-n/ 2 products AE, BG, AF, BH, CE, DG, CF, DH, and then do a few O(n^2 )- time additions. The total running time is described by the recurrence relation
T (n) = 8T (n/2) + O(n^2 ).
This comes out to an unimpressive O(n^3 ), the same as for the default algorithm. But the efficiency can be further improved, and as with integer multiplication, the key is some clever algebra. It turns out XY can be computed from just seven n/ 2 × n/ 2 subproblems, via a decomposition so tricky and intricate that one wonders how Strassen was ever able to discover it!
XY =
where
The new running time is T (n) = 7 T (n/2) + O(n^2 ),
which by the master theorem works out to O(nlog^2 7 ) ≈ O(n^2.^81 ).
68 Algorithms
We have so far seen how divide-and-conquer gives fast algorithms for multiplying integers and matrices; our next target is polynomials. The product of two degree-d polynomials is a polynomial of degree 2 d, for example:
(1 + 2x + 3x^2 ) · (2 + x + 4x^2 ) = 2 + 5x + 12x^2 + 11x^3 + 12x^4.
More generally, if A(x) = a 0 + a 1 x + · · · + adxd^ and B(x) = b 0 + b 1 x + · · · + bdxd, their product C(x) = A(x) · B(x) = c 0 + c 1 x + · · · + c 2 dx^2 d^ has coefficients
ck = a 0 bk + a 1 bk− 1 + · · · + akb 0 =
∑^ k
i=
aibk−i
(for i > d, take ai and bi to be zero). Computing ck from this formula takes O(k) steps, and finding all 2 d + 1 coefficients would therefore seem to require Θ(d^2 ) time. Can we possibly multiply polynomials faster than this? The solution we will develop, the fast Fourier transform, has revolutionized—indeed, defined—the field of signal processing (see the following box). Because of its huge impor- tance, and its wealth of insights from different fields of study, we will approach it a little more leisurely than usual. The reader who wants just the core algorithm can skip directly to Section 2.6.4.
70 Algorithms
To arrive at a fast algorithm for polynomial multiplication we take inspiration from an impor- tant property of polynomials.
Fact A degree-d polynomial is uniquely characterized by its values at any d + 1 distinct points.
A familiar instance of this is that “any two points determine a line.” We will later see why the more general statement is true (page 76), but for the time being it gives us an alternative representation of polynomials. Fix any distinct points x 0 ,... , xd. We can specify a degree-d polynomial A(x) = a 0 + a 1 x + · · · + adxd^ by either one of the following:
Of these two representations, the second is the more attractive for polynomial multiplication. Since the product C(x) has degree 2 d, it is completely determined by its value at any 2 d + 1 points. And its value at any given point z is easy enough to figure out, just A(z) times B(z). Thus polynomial multiplication takes linear time in the value representation. The problem is that we expect the input polynomials, and also their product, to be specified by coefficients. So we need to first translate from coefficients to values—which is just a matter of evaluating the polynomial at the chosen points—then multiply in the value representation, and finally translate back to coefficients, a process called interpolation.
Interpolation
Coefficient representation a 0 , a 1 ,... , ad
Value representation A(x 0 ), A(x 1 ),... , A(xd)
Evaluation
Figure 2.5 presents the resulting algorithm. The equivalence of the two polynomial representations makes it clear that this high-level approach is correct, but how efficient is it? Certainly the selection step and the n multiplica- tions are no trouble at all, just linear time.^3 But (leaving aside interpolation, about which we know even less) how about evaluation? Evaluating a polynomial of degree d ≤ n at a single point takes O(n) steps (Exercise 2.29), and so the baseline for n points is Θ(n^2 ). We’ll now see that the fast Fourier transform (FFT) does it in just O(n log n) time, for a particularly clever choice of x 0 ,... , xn− 1 in which the computations required by the individual points overlap with one another and can be shared.
(^3) In a typical setting for polynomial multiplication, the coefficients of the polynomials are real numbers and, moreover, are small enough that basic arithmetic operations (adding and multiplying) take unit time. We will assume this to be the case without any great loss of generality; in particular, the time bounds we obtain are easily adjustable to situations with larger numbers.
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 71
Figure 2.5 Polynomial multiplication
Input: Coefficients of two polynomials, A(x) and B(x), of degree d Output: Their product C = A · B
Selection Pick some points x 0 , x 1 ,... , xn− 1 , where n ≥ 2 d + 1 Evaluation Compute A(x 0 ), A(x 1 ),... , A(xn− 1 ) and B(x 0 ), B(x 1 ),... , B(xn− 1 ) Multiplication Compute C(xk) = A(xk)B(xk) for all k = 0,... , n − 1 Interpolation Recover C(x) = c 0 + c 1 x + · · · + c 2 dx^2 d
Here’s an idea for how to pick the n points at which to evaluate a polynomial A(x) of degree ≤ n − 1. If we choose them to be positive-negative pairs, that is,
±x 0 , ±x 1 ,... , ±xn/ 2 − 1 ,
then the computations required for each A(xi) and A(−xi) overlap a lot, because the even powers of xi coincide with those of −xi. To investigate this, we need to split A(x) into its odd and even powers, for instance
3 + 4x + 6x^2 + 2x^3 + x^4 + 10x^5 = (3 + 6x^2 + x^4 ) + x(4 + 2x^2 + 10x^4 ).
Notice that the terms in parentheses are polynomials in x^2. More generally,
A(x) = Ae(x^2 ) + xAo(x^2 ),
where Ae(·), with the even-numbered coefficients, and Ao(·), with the odd-numbered coeffi- cients, are polynomials of degree ≤ n/ 2 − 1 (assume for convenience that n is even). Given paired points ±xi, the calculations needed for A(xi) can be recycled toward computing A(−xi):
A(xi) = Ae(x^2 i ) + xiAo(x^2 i ) A(−xi) = Ae(x^2 i ) − xiAo(x^2 i ).
In other words, evaluating A(x) at n paired points ±x 0 ,... , ±xn/ 2 − 1 reduces to evaluating Ae(x) and Ao(x) (which each have half the degree of A(x)) at just n/ 2 points, x^20 ,... , x^2 n/ 2 − 1.
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 73
Therefore, if we start with these numbers for some n that is a power of 2 , then at successive levels of recursion we will have the (n/ 2 k)th roots of unity, for k = 0, 1 , 2 , 3 ,.. .. All these sets of numbers are plus-minus paired, and so our divide-and-conquer, as shown in the last panel, works perfectly. The resulting algorithm is the fast Fourier transform (Figure 2.7).
74 Algorithms
Figure 2.6 The complex roots of unity are ideal for our divide-and-conquer scheme.
θ Real
Imaginary
a
b
r
The complex plane z = a + bi is plotted at position (a, b). Polar coordinates: rewrite as z = r(cos θ + i sin θ) = reiθ^ , denoted (r, θ).
√ a^2 + b^2.
Examples: Number^ −^1 i^ 5 + 5i Polar coords (1, π) (1, π/2) (
√ 2 , π/4)
(r 1 r 2 , θ 1 + θ 2 )
(r 1 , θ 1 ) (r 2 , θ 2 )
Multiplying is easy in polar coordinates
Multiply the lengths and add the angles: (r 1 , θ 1 ) × (r 2 , θ 2 ) = (r 1 r 2 , θ 1 + θ 2 ). For any z = (r, θ),
Angle (^2) nπ
4 π n
2 π n +^ π
The n th complex roots of unity Solutions to the equation zn^ = 1. By the multiplication rule: solutions are z = (1, θ), for θ a multiple of 2 π/n (shown here for n = 16). For even n:
Divide-and-conquer step
Evaluate Ae(x), Ao(x) at (n/2)nd roots
Stillpaired
Divide and conquer
Paired
Evaluate A(x) at nth roots of unity
(n is a power of 2)