








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 control of a large force is the same principle as the control of a few men: it is merely a question of dividing up their numbers. — Sun Zi, The Art of War (c. 400 C.E.), translated by Lionel Giles (1910)
Nothing is particularly hard if you divide it into small jobs. — Henry Ford
Mergesort is one of the earliest algorithms proposed for sorting. According to Donald Knuth, it was suggested by John von Neumann as early as 1945.
Input: S O R T I N G E X A M P L Divide: S O R T I N G E X A M P L Recurse: I N O S R T A E G L M P X Merge: A E G I L M N O P S R T X A Mergesort example.
The first step is completely trivial—we only need to compute the median index m —and we can delegate the second step to the Recursion Fairy. All the real work is done in the final step; the two sorted subarrays A [ 1 .. m ] and A [ m + 1 .. n ] can be merged using a simple linear-time algorithm. Here’s a complete specification of the Mergesort algorithm; for simplicity, we separate out the merge step as a subroutine.
MERGESORT( A [1 .. n ]): if ( n > 1 ) m ← b n/ 2 c MERGESORT( A [1 .. m ]) MERGESORT( A [ m + 1 .. n ]) MERGE( A [1 .. n ], m )
MERGE( A [1 .. n ], m ): i ← 1; j ← m + 1 for k ← 1 to n if j > n B [ k ] ← A [ i ]; i ← i + 1 else if i > m B [ k ] ← A [ j ]; j ← j + 1 else if A [ i ] < A [ j ] B [ k ] ← A [ i ]; i ← i + 1 else B [ k ] ← A [ j ]; j ← j + 1 for k ← 1 to n A [ k ] ← B [ k ]
To prove that the algorithm is correct, we use our old friend induction. We can prove that MERGE is correct using induction on the total size of the two subarrays A [ i .. m ] and A [ j .. n ] left to be merged into B [ k .. n ]. The base case, where at least one subarray is empty, is straightforward; the algorithm just copies it into B. Otherwise, the smallest remaining element is either A [ i ] or A [ j ], since both subarrays are sorted, so B [ k ] is assigned correctly. The remaining subarrays—either A [ i + 1 .. m ] and A [ j .. n ], or
A [ i .. m ] and A [ j + 1 .. n ]—are merged correctly into B [ k + 1 .. n ] by the inductive hypothesis.^1 This completes the proof. Now we can prove MERGESORT correct by another round of straightforward induction.^2 The base cases n ≤ 1 are trivial. Otherwise, by the inductive hypothesis, the two smaller subarrays A [ 1 .. m ] and A [ m + 1 .. n ] are sorted correctly, and by our earlier argument, merged into the correct sorted output. What’s the running time? Since we have a recursive algorithm, we’re going to get a recurrence of some sort. MERGE clearly takes linear time, since it’s a simple for-loop with constant work per iteration. We get the following recurrence for MERGESORT:
T ( 1 ) = O ( 1 ), T ( n ) = T
d n/ 2 e
b n/ 2 c
Except for the floor and ceiling, this recurrence falls firmly into the “all levels equal” case of the recursion tree method, or its corollary, the Master Theorem. If we simply ignore the floor and ceiling, the method suggests the solution T ( n ) = O ( n log n ). We can easily check that this answer is correct using induction, but there is a simple method for solving recurrences like this directly, called domain transformation. First we overestimate the time bound, once by pretending that the two subproblem sizes are equal, and again to eliminate the ceiling:
T ( n ) ≤ 2 T
d n/ 2 e
Now we define a new function S ( n ) = T ( n + α ), where α is a constant chosen so that S ( n ) satisfies the familiar recurrence S ( n ) ≤ 2 S ( n/ 2 ) + O ( n ). To figure out the appropriate value for α , we compare two versions of the recurrence for T ( n + α ):
S ( n ) ≤ 2 S ( n/ 2 ) + O ( n ) =⇒ T ( n + α ) ≤ 2 T ( n/ 2 + α ) + O ( n ) T ( n ) ≤ 2 T ( n/ 2 + 1 ) + O ( n ) =⇒ T ( n + α ) ≤ 2 T (( n + α ) / 2 + 1 ) + O ( n + α )
For these two recurrences to be equal, we need n/ 2 + α = ( n + α ) / 2 + 1, which implies that α = 2. The recursion tree method tells us that S ( n ) = O ( n log n ), so
T ( n ) = S ( n − 2 ) = O (( n − 2 ) log( n − 2 )) = O ( n log n ). We can use domain transformations to remove floors, ceilings, and lower order terms from any recurrence. But now that we know this, we won’t bother actually grinding through the details!
Quicksort was discovered by Tony Hoare in 1962. In this algorithm, the hard work is splitting the array into subsets so that merging the final result is trivial.
we can still have k = 2 or k = n − 1 in the worst case. With the median-of-three heuristic, the recurrence becomes T ( n ) ≤ T ( 1 ) + T ( n − 2 ) + O ( n ), whose solution is still T ( n ) = O ( n^2 ). Intuitively, the pivot element will ‘usually’ fall somewhere in the middle of the array, say between n/ 10 and 9 n/ 10. This suggests that the average-case running time is O ( n log n ). Although this intuition is correct, we are still far from a proof that quicksort is usually efficient. We will formalize this intuition about average cases in a later lecture.
Both mergesort and and quicksort follow the same general three-step pattern of all divide and conquer algorithms:
If the size of any subproblem falls below some constant threshold, the recursion bottoms out. Hopefully, at that point, the problem is trivial, but if not, we switch to a different algorithm instead. Proving a divide-and-conquer algorithm correct usually involves strong induction. Analyzing the running time requires setting up and solving a recurrence, which often (but unfortunately not always!) can be solved using recursion trees (or, if you insist, the Master Theorem), perhaps after a simple domain transformation.
So, how do we find the median element of an array in linear time? The following algorithm was discovered by Manuel Blum, Bob Floyd, Vaughan Pratt, Ron Rivest, and Bob Tarjan in the early 1970s. Their algorithm actually solves the more general problem of selecting the k th largest element in an array, using the following recursive divide-and-conquer strategy. The subroutine PARTITION is the same as the one used in QUICKSORT.
SELECT( A [1 .. n ], r ): if n ≤ 25 use brute force else m ← d n/ 5 e for i ← 1 to m B [ i ] ← SELECT( A [ 5 i − 4 .. 5 i ], 3) 〈〈 Brute force! 〉〉 mom ← SELECT( B [1 .. m ], b m/ 2 c) 〈〈 Recursion! 〉〉 k ← PARTITION(SELECT( A [1 .. n ], mom ) if r > k return SELECT( A [1 .. k − 1 ], r ) else if r < k return SELECT( A [ k + 1 .. n ], r − k ) else return mom
If the input array is too large to handle by brute force, we divide it into d n/ 5 e blocks, each containing 5 elements, except possibly the last. (If the last block isn’t full, just throw in a few ∞s.) We find the median of each block by brute force and collect those medians into a new array. Then we recursively
compute the median of the new array (the median of medians — hence ‘mom’) and use it to partition the input array. Finally, either we get lucky and the median-of-medians is the r th largest element of A , or we recursively search one of the subarrays. The key insight is that the two subarrays cannot be too large or too small. The median-of-medians is larger than dd n/ 5 e / 2 e − 1 ≈ n/ 10 medians, and each of those medians is larger than two other elements in its block. In other words, the median-of-medians is larger than at least 3 n/ 10 elements in the input array. Symmetrically, mom is smaller than at least 3 n/ 10 input elements. Thus, in the worst case, the final recursive call searches an array of size 7 n/ 10. We conclude that the worst-case running time of the algorithm obeys the following recurrence:
T ( n ) ≤ O ( n ) + T ( n/ 5 ) + T ( 7 n/ 10 ).
The recursion tree method implies the solution T ( n ) = O ( n ). A finer analysis reveals that the hidden constants are quite large, even if we only count comparisons, which means this is not a practical algorithm for small inputs. (In particular, mergesort is faster in the worst case for all n < 4 , 000 , 000.) Selecting the median of 5 elements requires 6 comparisons, so we need 6 n/ 5 comparisons to set up the recursive subproblem. We need another n − 1 comparisons to partition the array after the recursive call returns. So the actual recurrence is
T ( n ) ≤ 11 n/ 5 + T ( n/ 5 ) + T ( 7 n/ 10 ).
The recursion tree method implies the upper bound
T ( n ) ≤
11 n 5
i ≥ 0
11 n 5
· 10 = 22 n.
Adding two n -digit numbers takes O ( n ) time by the standard iterative ‘ripple-carry’ algorithm, using a lookup table for each one-digit addition. Similarly, multiplying an n -digit number by a one-digit number takes O ( n ) time, using essentially the same algorithm. What about multiplying two n -digit numbers? At least in the United States, every grade school student (supposedly) learns to multiply by breaking the problem into n one-digit multiplications and n additions:
31415962 × 27182818 251327696 31415962 251327696 62831924 251327696 31415962 219911734 62831924 853974377340916
We could easily formalize this algorithm as a pair of nested for-loops. The algorithm runs in O ( n^2 ) time—altogether, there are O ( n^2 ) digits in the partial products, and for each digit, we spend constant time.
After a domain transformation, we can plug this into a recursion tree to get the solution T ( n ) = O ( n lg 3) = O ( n 1.585), a significant improvement over our earlier quadratic-time algorithm.^4 Of course, in practice, all this is done in binary instead of decimal. We can take this idea even further, splitting the numbers into more pieces and combining them in more complicated ways, to get even faster multiplication algorithms. Ultimately, this idea leads to the development of the Fast Fourier transform , a more complicated divide-and-conquer algorithm that can be used to multiply two n -digit numbers in O ( n log n ) time.^5 We’ll talk about Fast Fourier transforms in detail in another lecture.
Given a number a and a positive integer n , suppose we want to compute an. The standard naïve method is a simple for-loop that does n − 1 multiplications by a :
SLOWPOWER( a , n ): x ← a for i ← 2 to n x ← x · a return x
This iterative algorithm requires n multiplications. Notice that the input a could be an integer, or a rational, or a floating point number. In fact, it doesn’t need to be a number at all, as long as it’s something that we know how to multiply. For example, the same algorithm can be used to compute powers modulo some finite number (an operation commonly used in cryptography algorithms) or to compute powers of matrices (an operation used to evaluate recurrences and to compute shortest paths in graphs). All we really require is that a belong to a multiplicative group.^6 Since we don’t know what kind of things we’re multiplying, we can’t know how long a multiplication takes, so we’re forced analyze the running time in terms of the number of multiplications. There is a much faster divide-and-conquer method, using the simple formula an^ = a b n/^2 c^ · a d n/^2 e. What makes this approach more efficient is that once we compute the first factor a b n/^2 c, we can compute the second factor a d n/^2 e^ using at most one more multiplication.
FASTPOWER( a , n ): if n = 1 return a else x ← FASTPOWER( a , b n/ 2 c) if n is even return x · x else return x · x · a (^4) Karatsuba actually proposed an algorithm based on the formula ( a + c )( b + d ) − ac − bd = bc + ad. This algorithm also runs in O ( n lg 3) time, but the actual recurrence is a bit messier: a − b and c − d are still m -digit numbers, but a + b and c + d might have m + 1 digits. The simplification presented here is due to Donald Knuth. (^5) This fast algorithm for multiplying integers using FFTs was discovered by Arnold Schönhange and Volker Strassen in 1971. The O ( n log n ) running time requires the standard assumption that O (log n )-bit integer arithmetic can be performed in constant time; the number of bit operations is O ( n log n log log n ). (^6) A multiplicative group ( G , ⊗) is a set G and a function ⊗ : G × G → G , satisfying three axioms:
The total number of multiplications is given by the recurrence T ( n ) ≤ T (b n/ 2 c) + 2, with the base case T ( 1 ) = 0. After a domain transformation, recursion trees give us the solution T ( n ) = O (log n ). Incidentally, this algorithm is asymptotically optimal—any algorithm for computing an^ must perform Ω(log n ) multiplications. In fact, when n is a power of two, this algorithm is exactly optimal. However, there are slightly faster methods for other values of n. For example, our divide-and-conquer algorithm computes a^15 in six multiplications ( a^15 = a^7 · a^7 · a ; a^7 = a^3 · a^3 · a ; a^3 = a · a · a ), but only five multiplications are necessary ( a → a^2 → a^3 → a^5 → a^10 → a^15 ). Nobody knows of an efficient algorithm that always uses the minimum possible number of multiplications.
This last example combines the divide-and-conquer strategy with recursive backtracking. You all remember that the cost of a successful search in a binary search tree is proportional to the number of ancestors of the target node.^7 As a result, the worst-case search time is proportional to the depth of the tree. To minimize the worst-case search time, the height of the tree should be as small as possible; ideally, the tree is perfectly balanced. In many applications of binary search trees, it is more important to minimize the total cost of several searches than to minimize the worst-case cost of a single search. If x is a more ‘popular’ search target than y , we can save time by building a tree where the depth of x is smaller than the depth of y , even if that means increasing the overall depth of the tree. A perfectly balanced tree is not the best choice if some items are significantly more popular than others. In fact, a totally unbalanced tree of depth Ω( n ) might actually be the best choice! This situation suggests the following problem. Suppose we are given a sorted array of n keys A [ 1 .. n ] and an array of corresponding access frequencies f [ 1 .. n ]. Over the lifetime of the search tree, we will search for the key A [ i ] exactly f [ i ] times. Our task is to build the binary search tree that minimizes the total search time. Before we think about how to solve this problem, we should first come up with a good recursive definition of the function we are trying to optimize! Suppose we are also given a binary search tree T with n nodes. Let vi denote the node that stores A [ i ], and let r be the index of the root node. Ignoring constant factors, the cost of searching for A [ i ] is the number of nodes on the path from the root vr to vi. Thus, the total cost of performing all the binary searches is given by the following expression:
Cost ( T , f [1 .. n ]) =
∑^ n
i = 1
f [ i ] · #nodes between vr and vi
Every search path includes the root node vr. If i < r , then all other nodes on the search path to vi are in the left subtree; similarly, if i > r , all other nodes on the search path to vi are in the right subtree. Thus, we can partition the cost function into three parts as follows:
Cost ( T , f [1 .. n ]) =
r ∑− 1
i = 1
f [ i ] · #nodes between left ( vr ) and vi
∑^ n
i = 1
f [ i ]
∑^ n
i = r + 1
f [ i ] · #nodes between right ( vr ) and vi
(^7) An ancestor of a node v is either the node itself or an ancestor of the parent of v. A proper ancestor of v is either the parent of v or a proper ancestor of the parent of v.
which has the closed-from solution N ( n ) = Θ( 4 n/
p n ). Our algorithm saves considerable time by searching independently for the optimal left and right subtrees. A full enumeration of binary search trees would consider all possible pairings of left and right subtrees; hence the product in the recurrence for N ( n ).
Two algorithms for rotating a pixel map. Black arrows indicate blitting the blocks into place; white arrows indicate recursively rotating the blocks.
The first rotation algorithm (blit then recurse) in action.
(a) Prove that both versions of the algorithm are correct when n is a power of two. (b) Exactly how many blits does the algorithm perform when n is a power of two? (c) Describe how to modify the algorithm so that it works for arbitrary n , not just powers of two. How many blits does your modified algorithm perform? (d) What is your algorithm’s running time if a k × k blit takes O ( k^2 ) time? (e) What if a k × k blit takes only O ( k ) time?
A kd-tree for 15 points. The dashed line crosses the four shaded cells.
(a) How many cells are there, as a function of n? Prove your answer is correct. (b) In the worst case, exactly how many cells can a horizontal line cross, as a function of n? Prove your answer is correct. Assume that n = 2 k^ − 1 for some integer k. (c) Suppose we have n points stored in a kd-tree. Describe and analyze an algorithm that counts the number of points above a horizontal line (such as the dashed line in the figure) as quickly as possible. [Hint: Use part (b).] (d) Describe an analyze an efficient algorithm that counts, given a kd-tree storing n points, the number of points that lie inside a rectangle R with horizontal and vertical sides. [Hint: Use part (c).]
(a) Suppose a majority (more than half) of the delegates are from the same political party. Describe an efficient algorithm that identifies a member ( any member) of the majority party. (b) Now suppose exactly k political parties are represented at the convention and one party has a plurality : more delegates belong to that party than to any other. Present a practical procedure to pick a person from the plurality political party as parsimoniously as possible. (Please.)
FACTORIAL( n ): if n = 0 return 0 else return n · FACTORIAL( n − 1 )
(a) How many multiplications does this algorithm perform? (b) How many bits are required to write n! in binary? Express your answer in the form Θ( f ( n )), for some familiar function f ( n ). [Hint: Use Stirling’s approximation: n! ≈
p 2 πn · ( n/e ) n .] (c) Your answer to (b) should convince you that the number of multiplications is not a good estimate of the actual running time of FACTORIAL. The grade-school multiplication algorithm takes O ( k · l ) time to multiply a k -digit number and an l -digit number. What is the running time of FACTORIAL if we use this multiplication algorithm as a subroutine? (d) The following algorithm also computes n !, but groups the multiplication differently: FACTORIAL 2 ( n , m ): 〈〈 Compute n! / ( n − m )!〉〉 if m = 0 return 1 else if m = 1 return n else return FACTORIAL 2 ( n , b m/ 2 c) · FACTORIAL 2 ( n − b m/ 2 c, d m/ 2 e) What is the running time of FACTORIAL 2 ( n , n ) if we use grade-school multiplication? [Hint: Ignore the floors and ceilings.] (e) Describe and analyze a variant of Karastuba’s algorithm that can multiply any k -digit number and any l -digit number, where k ≥ l , in O ( k · l lg 3−^1 ) = O ( k · l 0.585) time. (f) What are the running times of FACTORIAL( n ) and FACTORIAL 2 ( n , n ) if we use the modified Karatsuba multiplication from part (e)?
© c Copyright 2008 Jeff Erickson. Released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License (http://creativecommons.org/licenses/by-nc-sa/3.0/). Free distribution is strongly encouraged; commercial distribution is expressly forbidden. See http://www.cs.uiuc.edu/~jeffe/teaching/algorithms/ for the most recent revision.