





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!






Look around you. Computers and networks are everywhere, enabling an intricate web of com- plex human activities: education, commerce, entertainment, research, manufacturing, health management, human communication, even war. Of the two main technological underpinnings of this amazing proliferation, one is obvious: the breathtaking pace with which advances in microelectronics and chip design have been bringing us faster and faster hardware. This book tells the story of the other intellectual enterprise that is crucially fueling the computer revolution: efficient algorithms. It is a fascinating story. Gather ’round and listen close.
Two ideas changed the world. In 1448 in the German city of Mainz a goldsmith named Jo- hann Gutenberg discovered a way to print books by putting together movable metallic pieces. Literacy spread, the Dark Ages ended, the human intellect was liberated, science and tech- nology triumphed, the Industrial Revolution happened. Many historians say we owe all this to typography. Imagine a world in which only an elite could read these lines! But others insist that the key development was not typography, but algorithms. Today we are so used to writing numbers in decimal, that it is easy to forget that Guten- berg would write the number 1448 as MCDXLVIII. How do you add two Roman numerals? What is MCDXLVIII + DCCCXII? (And just try to think about multiplying them.) Even a clever man like Gutenberg probably only knew how to add and subtract small numbers using his fingers; for anything more complicated he had to consult an abacus specialist. The decimal system, invented in India around AD 600, was a revolution in quantitative reasoning: using only 10 symbols, even very large numbers could be written down compactly, and arithmetic could be done efficiently on them by following elementary steps. Nonetheless these ideas took a long time to spread, hindered by traditional barriers of language, distance, and ignorance. The most influential medium of transmission turned out to be a textbook, written in Arabic in the ninth century by a man who lived in Baghdad. Al Khwarizmi laid out the basic methods for adding, multiplying, and dividing numbers—even extracting square roots and calculating digits of π. These procedures were precise, unambiguous, mechanical,
11
12 Algorithms
efficient, correct—in short, they were algorithms , a term coined to honor the wise man after the decimal system was finally adopted in Europe, many centuries later. Since then, this decimal positional system and its numerical algorithms have played an enormous role in Western civilization. They enabled science and technology; they acceler- ated industry and commerce. And when, much later, the computer was finally designed, it explicitly embodied the positional system in its bits and words and arithmetic unit. Scien- tists everywhere then got busy developing more and more complex algorithms for all kinds of problems and inventing novel applications—ultimately changing the world.
Al Khwarizmi’s work could not have gained a foothold in the West were it not for the efforts of one man: the 15th century Italian mathematician Leonardo Fibonacci, who saw the potential of the positional system and worked hard to develop it further and propagandize it. But today Fibonacci is most widely known for his famous sequence of numbers
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,... ,
each the sum of its two immediate predecessors. More formally, the Fibonacci numbers Fn are generated by the simple rule
Fn =
Fn− 1 + Fn− 2 if n > 1 1 if n = 1 0 if n = 0.
No other sequence of numbers has been studied as extensively, or applied to more fields: biology, demography, art, architecture, music, to name just a few. And, together with the powers of 2, it is computer science’s favorite sequence. In fact, the Fibonacci numbers grow almost as fast as the powers of 2: for example, F 30 is over a million, and F 100 is already 21 digits long! In general, Fn ≈ 20.^694 n^ (see Exercise 0.3). But what is the precise value of F 100 , or of F 200? Fibonacci himself would surely have wanted to know such things. To answer, we need an algorithm for computing the nth Fibonacci number.
An exponential algorithm
One idea is to slavishly implement the recursive definition of Fn. Here is the resulting algo- rithm, in the “pseudocode” notation used throughout this book:
function fib1(n) if n = 0: return 0 if n = 1: return 1 return fib1(n − 1 ) + fib1(n − 2 )
Whenever we have an algorithm, there are three questions we always ask about it:
14 Algorithms
Figure 0.1 The proliferation of recursive calls in fib1.
function fib2(n) if n = 0 return 0 create an array f[ 0... n] f[ 0 ] = 0, f[ 1 ] = 1 for i = 2... n: f[i] = f[i − 1 ] + f[i − 2 ] return f[n]
As with fib1, the correctness of this algorithm is self-evident because it directly uses the definition of Fn. How long does it take? The inner loop consists of a single computer step and is executed n − 1 times. Therefore the number of computer steps used by fib2 is linear in n. From exponential we are down to polynomial , a huge breakthrough in running time. It is now perfectly reasonable to compute F 200 or even F 200 , 000.^1 As we will see repeatedly throughout this book, the right algorithm makes all the differ- ence.
More careful analysis
In our discussion so far, we have been counting the number of basic computer steps executed by each algorithm and thinking of these basic steps as taking a constant amount of time. This is a very useful simplification. After all, a processor’s instruction set has a variety of basic primitives—branching, storing to memory, comparing numbers, simple arithmetic, and
(^1) To better appreciate the importance of this dichotomy between exponential and polynomial algorithms, the reader may want to peek ahead to the story of Sissa and Moore, in Chapter 8.
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 15
so on—and rather than distinguishing between these elementary operations, it is far more convenient to lump them together into one category. But looking back at our treatment of Fibonacci algorithms, we have been too liberal with what we consider a basic step. It is reasonable to treat addition as a single computer step if small numbers are being added, 32-bit numbers say. But the nth Fibonacci number is about
We’ve just seen how sloppiness in the analysis of running times can lead to an unacceptable level of inaccuracy in the result. But the opposite danger is also present: it is possible to be too precise. An insightful analysis is based on the right simplifications. Expressing running time in terms of basic computer steps is already a simplification. After all, the time taken by one such step depends crucially on the particular processor and even on details such as caching strategy (as a result of which the running time can differ subtly from one execution to the next). Accounting for these architecture-specific minutiae is a nightmar- ishly complex task and yields a result that does not generalize from one computer to the next. It therefore makes more sense to seek an uncluttered, machine-independent characterization of an algorithm’s efficiency. To this end, we will always express running time by counting the number of basic computer steps, as a function of the size of the input. And this simplification leads to another. Instead of reporting that an algorithm takes, say, 5 n^3 + 4n + 3 steps on an input of size n, it is much simpler to leave out lower-order terms such as 4 n and 3 (which become insignificant as n grows), and even the detail of the coefficient 5 in the leading term (computers will be five times faster in a few years anyway), and just say that the algorithm takes time O(n^3 ) (pronounced “big oh of n^3 ”). It is time to define this notation precisely. In what follows, think of f (n) and g(n) as the running times of two algorithms on inputs of size n.
Let f (n) and g(n) be functions from positive integers to positive reals. We say f = O(g) (which means that “f grows no faster than g”) if there is a constant c > 0 such that f (n) ≤ c · g(n).
Saying f = O(g) is a very loose analog of “f ≤ g.” It differs from the usual notion of ≤ because of the constant c, so that for instance 10 n = O(n). This constant also allows us to
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 17
In the preceding example, f 2 = Θ(f 3 ) and f 1 = Ω(f 3 ).
Big-O notation lets us focus on the big picture. When faced with a complicated function like 3 n^2 + 4n + 5, we just replace it with O(f (n)), where f (n) is as simple as possible. In this particular example we’d use O(n^2 ), because the quadratic portion of the sum dominates the rest. Here are some commonsense rules that help simplify functions by omitting dominated terms:
Don’t misunderstand this cavalier attitude toward constants. Programmers and algorithm developers are very interested in constants and would gladly stay up nights in order to make an algorithm run faster by a factor of 2. But understanding algorithms at the level of this book would be impossible without the simplicity afforded by big-O notation.
18 Algorithms
0.1. In each of the following situations, indicate whether f = O(g), or f = Ω(g), or both (in which case f = Θ(g)). f (n) g(n) (a) n − 100 n − 200 (b) n^1 /^2 n^2 /^3 (c) 100 n + log n n + (log n)^2 (d) n log n 10 n log 10n (e) log 2n log 3n (f) 10 log n log(n^2 ) (g) n^1.^01 n log^2 n (h) n^2 / log n n(log n)^2 (i) n^0.^1 (log n)^10 (j) (log n)log^ n^ n/ log n (k)
√ n (log n)^3 (l) n^1 /^2 5 log^2 n (m) n 2 n^3 n (n) 2 n^2 n+ (o) n! 2 n (p) (log n)log^ n^2 (log^2 n)^2 (q) ∑n i=1 ik^ nk+ 0.2. Show that, if c is a positive real number, then g(n) = 1 + c + c^2 + · · · + cn^ is:
(a) Θ(1) if c < 1. (b) Θ(n) if c = 1. (c) Θ(cn) if c > 1.
The moral: in big-Θ terms, the sum of a geometric series is simply the first term if the series is strictly decreasing, the last term if the series is strictly increasing, or the number of terms if the series is unchanging. 0.3. The Fibonacci numbers F 0 , F 1 , F 2 ,... , are defined by the rule F 0 = 0, F 1 = 1, Fn = Fn− 1 + Fn− 2.
In this problem we will confirm that this sequence grows exponentially fast and obtain some bounds on its growth. (a) Use induction to prove that Fn ≥ 20.^5 n^ for n ≥ 6. (b) Find a constant c < 1 such that Fn ≤ 2 cn^ for all n ≥ 0. Show that your answer is correct. (c) What is the largest c you can find for which Fn = Ω(2cn)? 0.4. Is there a faster way to compute the nth Fibonacci number than by fib2 (page 13)? One idea involves matrices. We start by writing the equations F 1 = F 1 and F 2 = F 0 + F 1 in matrix notation: ( F 1 F 2
( 0 1 1 1
) ·
( F 0 F 1
) .