Your SlideShare is downloading. ×
Introduction to algorithms
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Introduction to algorithms

2,850
views

Published on

Introduction to Algorithms, Second Edition, Thomas H. Cormen …

Introduction to Algorithms, Second Edition, Thomas H. Cormen
Charles E. Leiserson
Ronald L. Rivest
Clifford Stein

Published in: Education

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,850
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
98
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Introduction to Algorithms, Second EditionThomas H. CormenCharles E. LeisersonRonald L. RivestClifford SteinThe MIT PressCambridge , Massachusetts London, EnglandMcGraw-Hill Book CompanyBoston Burr Ridge , IL Dubuque , IA Madison , WI New York San Francisco St. LouisMontréal TorontoThis book is one of a series of texts written by faculty of the Electrical Engineering andComputer Science Department at the Massachusetts Institute of Technology. It was edited andproduced by The MIT Press under a joint production-distribution agreement with theMcGraw-Hill Book Company.Ordering Information:North AmericaText orders should be addressed to the McGraw-Hill Book Company. All other orders shouldbe addressed to The MIT Press.Outside North AmericaAll orders should be addressed to The MIT Press or its local distributor.Copyright © 2001 by The Massachusetts Institute of TechnologyFirst edition 1990All rights reserved. No part of this book may be reproduced in any form or by any electronicor mechanical means (including photocopying, recording, or information storage andretrieval) without permission in writing from the publisher.This book was printed and bound in the United States of America.Library of Congress Cataloging-in-Publication DataIntroduction to algorithms / Thomas H. Cormen ... [et al.].-2nd ed. p. cm. Includes bibliographical references and index.ISBN 0-262-03293-7 (hc.: alk. paper, MIT Press).-ISBN 0-07-013151-1 (McGraw-Hill)1. Computer programming. 2. Computer algorithms. I. Title: Algorithms. II. Cormen, ThomasH.QA76.6 I5858 2001
  • 2. 005.1-dc212001031277PrefaceThis book provides a comprehensive introduction to the modern study of computeralgorithms. It presents many algorithms and covers them in considerable depth, yet makestheir design and analysis accessible to all levels of readers. We have tried to keepexplanations elementary without sacrificing depth of coverage or mathematical rigor.Each chapter presents an algorithm, a design technique, an application area, or a related topic.Algorithms are described in English and in a "pseudocode" designed to be readable by anyonewho has done a little programming. The book contains over 230 figures illustrating how thealgorithms work. Since we emphasize efficiency as a design criterion, we include carefulanalyses of the running times of all our algorithms.The text is intended primarily for use in undergraduate or graduate courses in algorithms ordata structures. Because it discusses engineering issues in algorithm design, as well asmathematical aspects, it is equally well suited for self-study by technical professionals.In this, the second edition, we have updated the entire book. The changes range from theaddition of new chapters to the rewriting of individual sentences.To the teacherThis book is designed to be both versatile and complete. You will find it useful for a varietyof courses, from an undergraduate course in data structures up through a graduate course inalgorithms. Because we have provided considerably more material than can fit in a typicalone-term course, you should think of the book as a "buffet" or "smorgasbord" from which youcan pick and choose the material that best supports the course you wish to teach.You should find it easy to organize your course around just the chapters you need. We havemade chapters relatively self-contained, so that you need not worry about an unexpected andunnecessary dependence of one chapter on another. Each chapter presents the easier materialfirst and the more difficult material later, with section boundaries marking natural stoppingpoints. In an undergraduate course, you might use only the earlier sections from a chapter; ina graduate course, you might cover the entire chapter.We have included over 920 exercises and over 140 problems. Each section ends withexercises, and each chapter ends with problems. The exercises are generally short questionsthat test basic mastery of the material. Some are simple self-check thought exercises, whereasothers are more substantial and are suitable as assigned homework. The problems are moreelaborate case studies that often introduce new material; they typically consist of severalquestions that lead the student through the steps required to arrive at a solution.We have starred (⋆) the sections and exercises that are more suitable for graduate studentsthan for undergraduates. A starred section is not necessarily more difficult than an unstarred
  • 3. one, but it may require an understanding of more advanced mathematics. Likewise, starredexercises may require an advanced background or more than average creativity.To the studentWe hope that this textbook provides you with an enjoyable introduction to the field ofalgorithms. We have attempted to make every algorithm accessible and interesting. To helpyou when you encounter unfamiliar or difficult algorithms, we describe each one in a step-by-step manner. We also provide careful explanations of the mathematics needed to understandthe analysis of the algorithms. If you already have some familiarity with a topic, you will findthe chapters organized so that you can skim introductory sections and proceed quickly to themore advanced material.This is a large book, and your class will probably cover only a portion of its material. Wehave tried, however, to make this a book that will be useful to you now as a course textbookand also later in your career as a mathematical desk reference or an engineering handbook.What are the prerequisites for reading this book? • You should have some programming experience. In particular, you should understand recursive procedures and simple data structures such as arrays and linked lists. • You should have some facility with proofs by mathematical induction. A few portions of the book rely on some knowledge of elementary calculus. Beyond that, Parts I and VIII of this book teach you all the mathematical techniques you will need.To the professionalThe wide range of topics in this book makes it an excellent handbook on algorithms. Becauseeach chapter is relatively self-contained, you can focus in on the topics that most interest you.Most of the algorithms we discuss have great practical utility. We therefore addressimplementation concerns and other engineering issues. We often provide practical alternativesto the few algorithms that are primarily of theoretical interest.If you wish to implement any of the algorithms, you will find the translation of ourpseudocode into your favorite programming language a fairly straightforward task. Thepseudocode is designed to present each algorithm clearly and succinctly. Consequently, we donot address error-handling and other software-engineering issues that require specificassumptions about your programming environment. We attempt to present each algorithmsimply and directly without allowing the idiosyncrasies of a particular programming languageto obscure its essence.To our colleaguesWe have supplied an extensive bibliography and pointers to the current literature. Eachchapter ends with a set of "chapter notes" that give historical details and references. Thechapter notes do not provide a complete reference to the whole field of algorithms, however.Though it may be hard to believe for a book of this size, many interesting algorithms couldnot be included due to lack of space.
  • 4. Despite myriad requests from students for solutions to problems and exercises, we havechosen as a matter of policy not to supply references for problems and exercises, to removethe temptation for students to look up a solution rather than to find it themselves.Changes for the second editionWhat has changed between the first and second editions of this book? Depending on how youlook at it, either not much or quite a bit.A quick look at the table of contents shows that most of the first-edition chapters and sectionsappear in the second edition. We removed two chapters and a handful of sections, but we haveadded three new chapters and four new sections apart from these new chapters. If you were tojudge the scope of the changes by the table of contents, you would likely conclude that thechanges were modest.The changes go far beyond what shows up in the table of contents, however. In no particularorder, here is a summary of the most significant changes for the second edition: • Cliff Stein was added as a coauthor. • Errors have been corrected. How many errors? Lets just say several. • There are three new chapters: o Chapter 1 discusses the role of algorithms in computing. o Chapter 5 covers probabilistic analysis and randomized algorithms. As in the first edition, these topics appear throughout the book. o Chapter 29 is devoted to linear programming. • Within chapters that were carried over from the first edition, there are new sections on the following topics: o perfect hashing (Section 11.5), o two applications of dynamic programming (Sections 15.1 and 15.5), and o approximation algorithms that use randomization and linear programming (Section 35.4). • To allow more algorithms to appear earlier in the book, three of the chapters on mathematical background have been moved from Part I to the Appendix, which is Part VIII. • There are over 40 new problems and over 185 new exercises. • We have made explicit the use of loop invariants for proving correctness. Our first loop invariant appears in Chapter 2, and we use them a couple of dozen times throughout the book. • Many of the probabilistic analyses have been rewritten. In particular, we use in a dozen places the technique of "indicator random variables," which simplify probabilistic analyses, especially when random variables are dependent. • We have expanded and updated the chapter notes and bibliography. The bibliography has grown by over 50%, and we have mentioned many new algorithmic results that have appeared subsequent to the printing of the first edition.We have also made the following changes: • The chapter on solving recurrences no longer contains the iteration method. Instead, in Section 4.2, we have "promoted" recursion trees to constitute a method in their own right. We have found that drawing out recursion trees is less error-prone than iterating
  • 5. recurrences. We do point out, however, that recursion trees are best used as a way to generate guesses that are then verified via the substitution method. • The partitioning method used for quicksort (Section 7.1) and the expected linear-time order-statistic algorithm (Section 9.2) is different. We now use the method developed by Lomuto, which, along with indicator random variables, allows for a somewhat simpler analysis. The method from the first edition, due to Hoare, appears as a problem in Chapter 7. • We have modified the discussion of universal hashing in Section 11.3.3 so that it integrates into the presentation of perfect hashing. • There is a much simpler analysis of the height of a randomly built binary search tree in Section 12.4. • The discussions on the elements of dynamic programming (Section 15.3) and the elements of greedy algorithms (Section 16.2) are significantly expanded. The exploration of the activity-selection problem, which starts off the greedy-algorithms chapter, helps to clarify the relationship between dynamic programming and greedy algorithms. • We have replaced the proof of the running time of the disjoint-set-union data structure in Section 21.4 with a proof that uses the potential method to derive a tight bound. • The proof of correctness of the algorithm for strongly connected components in Section 22.5 is simpler, clearer, and more direct. • Chapter 24, on single-source shortest paths, has been reorganized to move proofs of the essential properties to their own section. The new organization allows us to focus earlier on algorithms. • Section 34.5 contains an expanded overview of NP-completeness as well as new NP- completeness proofs for the hamiltonian-cycle and subset-sum problems.Finally, virtually every section has been edited to correct, simplify, and clarify explanationsand proofs.Web siteAnother change from the first edition is that this book now has its own web site:http://mitpress.mit.edu/algorithms/. You can use the web site to report errors, obtain a list ofknown errors, or make suggestions; we would like to hear from you. We particularly welcomeideas for new exercises and problems, but please include solutions.We regret that we cannot personally respond to all comments.Acknowledgments for the first editionMany friends and colleagues have contributed greatly to the quality of this book. We thank allof you for your help and constructive criticisms.MITs Laboratory for Computer Science has provided an ideal working environment. Ourcolleagues in the laboratorys Theory of Computation Group have been particularly supportiveand tolerant of our incessant requests for critical appraisal of chapters. We specifically thankBaruch Awerbuch, Shafi Goldwasser, Leo Guibas, Tom Leighton, Albert Meyer, DavidShmoys, and Éva Tardos. Thanks to William Ang, Sally Bemus, Ray Hirschfeld, and MarkReinhold for keeping our machines (DEC Microvaxes, Apple Macintoshes, and Sun
  • 6. Sparcstations) running and for recompiling whenever we exceeded a compile-time limit.Thinking Machines Corporation provided partial support for Charles Leiserson to work onthis book during a leave of absence from MIT.Many colleagues have used drafts of this text in courses at other schools. They have suggestednumerous corrections and revisions. We particularly wish to thank Richard Beigel, AndrewGoldberg, Joan Lucas, Mark Overmars, Alan Sherman, and Diane Souvaine.Many teaching assistants in our courses have made significant contributions to thedevelopment of this material. We especially thank Alan Baratz, Bonnie Berger, Aditi Dhagat,Burt Kaliski, Arthur Lent, Andrew Moulton, Marios Papaefthymiou, Cindy Phillips, MarkReinhold, Phil Rogaway, Flavio Rose, Arie Rudich, Alan Sherman, Cliff Stein, Susmita Sur,Gregory Troxel, and Margaret Tuttle.Additional valuable technical assistance was provided by many individuals. Denise Sergentspent many hours in the MIT libraries researching bibliographic references. Maria Sensale,the librarian of our reading room, was always cheerful and helpful. Access to Albert Meyerspersonal library saved many hours of library time in preparing the chapter notes. ShlomoKipnis, Bill Niehaus, and David Wilson proofread old exercises, developed new ones, andwrote notes on their solutions. Marios Papaefthymiou and Gregory Troxel contributed to theindexing. Over the years, our secretaries Inna Radzihovsky, Denise Sergent, Gayle Sherman,and especially Be Blackburn provided endless support in this project, for which we thankthem.Many errors in the early drafts were reported by students. We particularly thank BobbyBlumofe, Bonnie Eisenberg, Raymond Johnson, John Keen, Richard Lethin, Mark Lillibridge,John Pezaris, Steve Ponzio, and Margaret Tuttle for their careful readings.Colleagues have also provided critical reviews of specific chapters, or information on specificalgorithms, for which we are grateful. We especially thank Bill Aiello, Alok Aggarwal, EricBach, Vašek Chvátal, Richard Cole, Johan Hastad, Alex Ishii, David Johnson, Joe Kilian,Dina Kravets, Bruce Maggs, Jim Orlin, James Park, Thane Plambeck, Hershel Safer, JeffShallit, Cliff Stein, Gil Strang, Bob Tarjan, and Paul Wang. Several of our colleagues alsograciously supplied us with problems; we particularly thank Andrew Goldberg, DannySleator, and Umesh Vazirani.It has been a pleasure working with The MIT Press and McGraw-Hill in the development ofthis text. We especially thank Frank Satlow, Terry Ehling, Larry Cohen, and Lorrie Lejeuneof The MIT Press and David Shapiro of McGraw-Hill for their encouragement, support, andpatience. We are particularly grateful to Larry Cohen for his outstanding copyediting.Acknowledgments for the second editionWhen we asked Julie Sussman, P.P.A., to serve as a technical copyeditor for the secondedition, we did not know what a good deal we were getting. In addition to copyediting thetechnical content, Julie enthusiastically edited our prose. It is humbling to think of how manyerrors Julie found in our earlier drafts, though considering how many errors she found in thefirst edition (after it was printed, unfortunately), it is not surprising. Moreover, Julie sacrificedher own schedule to accommodate ours-she even brought chapters with her on a trip to theVirgin Islands! Julie, we cannot thank you enough for the amazing job you did.
  • 7. The work for the second edition was done while the authors were members of the Departmentof Computer Science at Dartmouth College and the Laboratory for Computer Science at MIT.Both were stimulating environments in which to work, and we thank our colleagues for theirsupport.Friends and colleagues all over the world have provided suggestions and opinions that guidedour writing. Many thanks to Sanjeev Arora, Javed Aslam, Guy Blelloch, Avrim Blum, ScotDrysdale, Hany Farid, Hal Gabow, Andrew Goldberg, David Johnson, Yanlin Liu, NicolasSchabanel, Alexander Schrijver, Sasha Shen, David Shmoys, Dan Spielman, Gerald JaySussman, Bob Tarjan, Mikkel Thorup, and Vijay Vazirani.Many teachers and colleagues have taught us a great deal about algorithms. We particularlyacknowledge our teachers Jon L. Bentley, Bob Floyd, Don Knuth, Harold Kuhn, H. T. Kung,Richard Lipton, Arnold Ross, Larry Snyder, Michael I. Shamos, David Shmoys, KenSteiglitz, Tom Szymanski, Éva Tardos, Bob Tarjan, and Jeffrey Ullman.We acknowledge the work of the many teaching assistants for the algorithms courses at MITand Dartmouth, including Joseph Adler, Craig Barrack, Bobby Blumofe, Roberto De Prisco,Matteo Frigo, Igal Galperin, David Gupta, Raj D. Iyer, Nabil Kahale, Sarfraz Khurshid,Stavros Kolliopoulos, Alain Leblanc, Yuan Ma, Maria Minkoff, Dimitris Mitsouras, AlinPopescu, Harald Prokop, Sudipta Sengupta, Donna Slonim, Joshua A. Tauber, Sivan Toledo,Elisheva Werner-Reiss, Lea Wittie, Qiang Wu, and Michael Zhang.Computer support was provided by William Ang, Scott Blomquist, and Greg Shomo at MITand by Wayne Cripps, John Konkle, and Tim Tregubov at Dartmouth. Thanks also to BeBlackburn, Don Dailey, Leigh Deacon, Irene Sebeda, and Cheryl Patton Wu at MIT and toPhyllis Bellmore, Kelly Clark, Delia Mauceli, Sammie Travis, Deb Whiting, and Beth Youngat Dartmouth for administrative support. Michael Fromberger, Brian Campbell, AmandaEubanks, Sung Hoon Kim, and Neha Narula also provided timely support at Dartmouth.Many people were kind enough to report errors in the first edition. We thank the followingpeople, each of whom was the first to report an error from the first edition: Len Adleman,Selim Akl, Richard Anderson, Juan Andrade-Cetto, Gregory Bachelis, David Barrington, PaulBeame, Richard Beigel, Margrit Betke, Alex Blakemore, Bobby Blumofe, Alexander Brown,Xavier Cazin, Jack Chan, Richard Chang, Chienhua Chen, Ien Cheng, Hoon Choi, DrueColes, Christian Collberg, George Collins, Eric Conrad, Peter Csaszar, Paul Dietz, MartinDietzfelbinger, Scot Drysdale, Patricia Ealy, Yaakov Eisenberg, Michael Ernst, MichaelFormann, Nedim Fresko, Hal Gabow, Marek Galecki, Igal Galperin, Luisa Gargano, JohnGately, Rosario Genario, Mihaly Gereb, Ronald Greenberg, Jerry Grossman, StephenGuattery, Alexander Hartemik, Anthony Hill, Thomas Hofmeister, Mathew Hostetter, Yih-Chun Hu, Dick Johnsonbaugh, Marcin Jurdzinki, Nabil Kahale, Fumiaki Kamiya, AnandKanagala, Mark Kantrowitz, Scott Karlin, Dean Kelley, Sanjay Khanna, Haluk Konuk, DinaKravets, Jon Kroger, Bradley Kuszmaul, Tim Lambert, Hang Lau, Thomas Lengauer, GeorgeMadrid, Bruce Maggs, Victor Miller, Joseph Muskat, Tung Nguyen, Michael Orlov, JamesPark, Seongbin Park, Ioannis Paschalidis, Boaz Patt-Shamir, Leonid Peshkin, PatricioPoblete, Ira Pohl, Stephen Ponzio, Kjell Post, Todd Poynor, Colin Prepscius, Sholom Rosen,Dale Russell, Hershel Safer, Karen Seidel, Joel Seiferas, Erik Seligman, Stanley Selkow,Jeffrey Shallit, Greg Shannon, Micha Sharir, Sasha Shen, Norman Shulman, Andrew Singer,Daniel Sleator, Bob Sloan, Michael Sofka, Volker Strumpen, Lon Sunshine, Julie Sussman,Asterio Tanaka, Clark Thomborson, Nils Thommesen, Homer Tilton, Martin Tompa, Andrei
  • 8. Toom, Felzer Torsten, Hirendu Vaishnav, M. Veldhorst, Luca Venuti, Jian Wang, MichaelWellman, Gerry Wiener, Ronald Williams, David Wolfe, Jeff Wong, Richard Woundy, NealYoung, Huaiyuan Yu, Tian Yuxing, Joe Zachary, Steve Zhang, Florian Zschoke, and UriZwick.Many of our colleagues provided thoughtful reviews or filled out a long survey. We thankreviewers Nancy Amato, Jim Aspnes, Kevin Compton, William Evans, Peter Gacs, MichaelGoldwasser, Andrzej Proskurowski, Vijaya Ramachandran, and John Reif. We also thank thefollowing people for sending back the survey: James Abello, Josh Benaloh, Bryan Beresford-Smith, Kenneth Blaha, Hans Bodlaender, Richard Borie, Ted Brown, Domenico Cantone, M.Chen, Robert Cimikowski, William Clocksin, Paul Cull, Rick Decker, Matthew Dickerson,Robert Douglas, Margaret Fleck, Michael Goodrich, Susanne Hambrusch, Dean Hendrix,Richard Johnsonbaugh, Kyriakos Kalorkoti, Srinivas Kankanahalli, Hikyoo Koh, StevenLindell, Errol Lloyd, Andy Lopez, Dian Rae Lopez, George Lucker, David Maier, CharlesMartel, Xiannong Meng, David Mount, Alberto Policriti, Andrzej Proskurowski, Kirk Pruhs,Yves Robert, Guna Seetharaman, Stanley Selkow, Robert Sloan, Charles Steele, Gerard Tel,Murali Varanasi, Bernd Walter, and Alden Wright. We wish we could have carried out allyour suggestions. The only problem is that if we had, the second edition would have beenabout 3000 pages long!The second edition was produced in . Michael Downes converted the macros from"classic" to , and he converted the text files to use these new macros. David Jonesalso provided support. Figures for the second edition were produced by the authorsusing MacDraw Pro. As in the first edition, the index was compiled using Windex, a Cprogram written by the authors, and the bibliography was prepared using . AyorkorMills-Tettey and Rob Leathern helped convert the figures to MacDraw Pro, and Ayorkor alsochecked our bibliography.As it was in the first edition, working with The MIT Press and McGraw-Hill has been adelight. Our editors, Bob Prior of The MIT Press and Betsy Jones of McGraw-Hill, put upwith our antics and kept us going with carrots and sticks.Finally, we thank our wives-Nicole Cormen, Gail Rivest, and Rebecca Ivry-our children-Ricky, William, and Debby Leiserson; Alex and Christopher Rivest; and Molly, Noah, andBenjamin Stein-and our parents-Renee and Perry Cormen, Jean and Mark Leiserson, Shirleyand Lloyd Rivest, and Irene and Ira Stein-for their love and support during the writing of thisbook. The patience and encouragement of our families made this project possible. Weaffectionately dedicate this book to them.THOMAS H. CORMENHanover, New HampshireCHARLES E. LEISERSONCambridge, MassachusettsRONALD L. RIVESTCambridge, MassachusettsCLIFFORD STEINHanover, New Hampshire
  • 9. May 2001Part I: FoundationsChapter ListChapter 1: The Role of Algorithms in ComputingChapter 2: Getting StartedChapter 3: Growth of FunctionsChapter 4: RecurrencesChapter 5: Probabilistic Analysis and Randomized AlgorithmsIntroductionThis part will get you started in thinking about designing and analyzing algorithms. It isintended to be a gentle introduction to how we specify algorithms, some of the designstrategies we will use throughout this book, and many of the fundamental ideas used inalgorithm analysis. Later parts of this book will build upon this base.Chapter 1 is an overview of algorithms and their place in modern computing systems. Thischapter defines what an algorithm is and lists some examples. It also makes a case thatalgorithms are a technology, just as are fast hardware, graphical user interfaces, object-oriented systems, and networks.In Chapter 2, we see our first algorithms, which solve the problem of sorting a sequence of nnumbers. They are written in a pseudocode which, although not directly translatable to anyconventional programming language, conveys the structure of the algorithm clearly enoughthat a competent programmer can implement it in the language of his choice. The sortingalgorithms we examine are insertion sort, which uses an incremental approach, and mergesort, which uses a recursive technique known as "divide and conquer." Although the timeeach requires increases with the value of n, the rate of increase differs between the twoalgorithms. We determine these running times in Chapter 2, and we develop a useful notationto express them.Chapter 3 precisely defines this notation, which we call asymptotic notation. It starts bydefining several asymptotic notations, which we use for bounding algorithm running timesfrom above and/or below. The rest of Chapter 3 is primarily a presentation of mathematicalnotation. Its purpose is more to ensure that your use of notation matches that in this book thanto teach you new mathematical concepts.Chapter 4 delves further into the divide-and-conquer method introduced in Chapter 2. Inparticular, Chapter 4 contains methods for solving recurrences, which are useful fordescribing the running times of recursive algorithms. One powerful technique is the "mastermethod," which can be used to solve recurrences that arise from divide-and-conqueralgorithms. Much of Chapter 4 is devoted to proving the correctness of the master method,though this proof may be skipped without harm.
  • 10. Chapter 5 introduces probabilistic analysis and randomized algorithms. We typically useprobabilistic analysis to determine the running time of an algorithm in cases in which, due tothe presence of an inherent probability distribution, the running time may differ on differentinputs of the same size. In some cases, we assume that the inputs conform to a knownprobability distribution, so that we are averaging the running time over all possible inputs. Inother cases, the probability distribution comes not from the inputs but from random choicesmade during the course of the algorithm. An algorithm whose behavior is determined not onlyby its input but by the values produced by a random-number generator is a randomizedalgorithm. We can use randomized algorithms to enforce a probability distribution on theinputs-thereby ensuring that no particular input always causes poor performance-or even tobound the error rate of algorithms that are allowed to produce incorrect results on a limitedbasis.Appendices A-C contain other mathematical material that you will find helpful as you readthis book. You are likely to have seen much of the material in the appendix chapters beforehaving read this book (although the specific notational conventions we use may differ in somecases from what you have seen in the past), and so you should think of the Appendices asreference material. On the other hand, you probably have not already seen most of thematerial in Part I. All the chapters in Part I and the Appendices are written with a tutorialflavor.Chapter 1: The Role of Algorithms inComputingWhat are algorithms? Why is the study of algorithms worthwhile? What is the role ofalgorithms relative to other technologies used in computers? In this chapter, we will answerthese questions.1.1 AlgorithmsInformally, an algorithm is any well-defined computational procedure that takes some value,or set of values, as input and produces some value, or set of values, as output. An algorithm isthus a sequence of computational steps that transform the input into the output.We can also view an algorithm as a tool for solving a well-specified computational problem.The statement of the problem specifies in general terms the desired input/output relationship.The algorithm describes a specific computational procedure for achieving that input/outputrelationship.For example, one might need to sort a sequence of numbers into nondecreasing order. Thisproblem arises frequently in practice and provides fertile ground for introducing manystandard design techniques and analysis tools. Here is how we formally define the sortingproblem: • Input: A sequence of n numbers a1, a2, ..., an . • Output: A permutation (reordering) of the input sequence such that .
  • 11. For example, given the input sequence 31, 41, 59, 26, 41, 58 , a sorting algorithm returnsas output the sequence 26, 31, 41, 41, 58, 59 . Such an input sequence is called an instanceof the sorting problem. In general, an instance of a problem consists of the input (satisfyingwhatever constraints are imposed in the problem statement) needed to compute a solution tothe problem.Sorting is a fundamental operation in computer science (many programs use it as anintermediate step), and as a result a large number of good sorting algorithms have beendeveloped. Which algorithm is best for a given application depends on-among other factors-the number of items to be sorted, the extent to which the items are already somewhat sorted,possible restrictions on the item values, and the kind of storage device to be used: mainmemory, disks, or tapes.An algorithm is said to be correct if, for every input instance, it halts with the correct output.We say that a correct algorithm solves the given computational problem. An incorrectalgorithm might not halt at all on some input instances, or it might halt with an answer otherthan the desired one. Contrary to what one might expect, incorrect algorithms can sometimesbe useful, if their error rate can be controlled. We shall see an example of this in Chapter 31when we study algorithms for finding large prime numbers. Ordinarily, however, we shall beconcerned only with correct algorithms.An algorithm can be specified in English, as a computer program, or even as a hardwaredesign. The only requirement is that the specification must provide a precise description of thecomputational procedure to be followed.What kinds of problems are solved by algorithms?Sorting is by no means the only computational problem for which algorithms have beendeveloped. (You probably suspected as much when you saw the size of this book.) Practicalapplications of algorithms are ubiquitous and include the following examples: • The Human Genome Project has the goals of identifying all the 100,000 genes in human DNA, determining the sequences of the 3 billion chemical base pairs that make up human DNA, storing this information in databases, and developing tools for data analysis. Each of these steps requires sophisticated algorithms. While the solutions to the various problems involved are beyond the scope of this book, ideas from many of the chapters in this book are used in the solution of these biological problems, thereby enabling scientists to accomplish tasks while using resources efficiently. The savings are in time, both human and machine, and in money, as more information can be extracted from laboratory techniques. • The Internet enables people all around the world to quickly access and retrieve large amounts of information. In order to do so, clever algorithms are employed to manage and manipulate this large volume of data. Examples of problems which must be solved include finding good routes on which the data will travel (techniques for solving such problems appear in Chapter 24), and using a search engine to quickly find pages on which particular information resides (related techniques are in Chapters 11 and 32). • Electronic commerce enables goods and services to be negotiated and exchanged electronically. The ability to keep information such as credit card numbers, passwords, and bank statements private is essential if electronic commerce is to be used widely.
  • 12. Public-key cryptography and digital signatures (covered in Chapter 31) are among the core technologies used and are based on numerical algorithms and number theory. • In manufacturing and other commercial settings, it is often important to allocate scarce resources in the most beneficial way. An oil company may wish to know where to place its wells in order to maximize its expected profit. A candidate for the presidency of the United States may want to determine where to spend money buying campaign advertising in order to maximize the chances of winning an election. An airline may wish to assign crews to flights in the least expensive way possible, making sure that each flight is covered and that government regulations regarding crew scheduling are met. An Internet service provider may wish to determine where to place additional resources in order to serve its customers more effectively. All of these are examples of problems that can be solved using linear programming, which we shall study in Chapter 29.While some of the details of these examples are beyond the scope of this book, we do giveunderlying techniques that apply to these problems and problem areas. We also show how tosolve many concrete problems in this book, including the following: • We are given a road map on which the distance between each pair of adjacent intersections is marked, and our goal is to determine the shortest route from one intersection to another. The number of possible routes can be huge, even if we disallow routes that cross over themselves. How do we choose which of all possible routes is the shortest? Here, we model the road map (which is itself a model of the actual roads) as a graph (which we will meet in Chapter 10 and Appendix B), and we wish to find the shortest path from one vertex to another in the graph. We shall see how to solve this problem efficiently in Chapter 24. • We are given a sequence A1, A2, ..., An of n matrices, and we wish to determine their product A1 A2 An. Because matrix multiplication is associative, there are several legal multiplication orders. For example, if n = 4, we could perform the matrix multiplications as if the product were parenthesized in any of the following orders: (A1(A2(A3A4))), (A1((A2A3)A4)), ((A1A2)(A3A4)), ((A1(A2A3))A4), or (((A1A2)A3)A4). If these matrices are all square (and hence the same size), the multiplication order will not affect how long the matrix multiplications take. If, however, these matrices are of differing sizes (yet their sizes are compatible for matrix multiplication), then the multiplication order can make a very big difference. The number of possible multiplication orders is exponential in n, and so trying all possible orders may take a very long time. We shall see in Chapter 15 how to use a general technique known as dynamic programming to solve this problem much more efficiently. • We are given an equation ax ≡ b (mod n), where a, b, and n are integers, and we wish to find all the integers x, modulo n, that satisfy the equation. There may be zero, one, or more than one such solution. We can simply try x = 0, 1, ..., n - 1 in order, but Chapter 31 shows a more efficient method. • We are given n points in the plane, and we wish to find the convex hull of these points. The convex hull is the smallest convex polygon containing the points. Intuitively, we can think of each point as being represented by a nail sticking out from a board. The convex hull would be represented by a tight rubber band that surrounds all the nails. Each nail around which the rubber band makes a turn is a vertex of the convex hull. (See Figure 33.6 on page 948 for an example.) Any of the 2n subsets of the points might be the vertices of the convex hull. Knowing which points are vertices of the convex hull is not quite enough, either, since we also need to know the order in
  • 13. which they appear. There are many choices, therefore, for the vertices of the convex hull. Chapter 33 gives two good methods for finding the convex hull.These lists are far from exhaustive (as you again have probably surmised from this booksheft), but exhibit two characteristics that are common to many interesting algorithms. 1. There are many candidate solutions, most of which are not what we want. Finding one that we do want can present quite a challenge. 2. There are practical applications. Of the problems in the above list, shortest paths provides the easiest examples. A transportation firm, such as a trucking or railroad company, has a financial interest in finding shortest paths through a road or rail network because taking shorter paths results in lower labor and fuel costs. Or a routing node on the Internet may need to find the shortest path through the network in order to route a message quickly.Data structuresThis book also contains several data structures. A data structure is a way to store andorganize data in order to facilitate access and modifications. No single data structure workswell for all purposes, and so it is important to know the strengths and limitations of several ofthem.TechniqueAlthough you can use this book as a "cookbook" for algorithms, you may someday encountera problem for which you cannot readily find a published algorithm (many of the exercises andproblems in this book, for example!). This book will teach you techniques of algorithm designand analysis so that you can develop algorithms on your own, show that they give the correctanswer, and understand their efficiency.Hard problemsMost of this book is about efficient algorithms. Our usual measure of efficiency is speed, i.e.,how long an algorithm takes to produce its result. There are some problems, however, forwhich no efficient solution is known. Chapter 34 studies an interesting subset of theseproblems, which are known as NP-complete.Why are NP-complete problems interesting? First, although no efficient algorithm for an NP-complete problem has ever been found, nobody has ever proven that an efficient algorithm forone cannot exist. In other words, it is unknown whether or not efficient algorithms exist forNP-complete problems. Second, the set of NP-complete problems has the remarkable propertythat if an efficient algorithm exists for any one of them, then efficient algorithms exist for allof them. This relationship among the NP-complete problems makes the lack of efficientsolutions all the more tantalizing. Third, several NP-complete problems are similar, but notidentical, to problems for which we do know of efficient algorithms. A small change to theproblem statement can cause a big change to the efficiency of the best known algorithm.It is valuable to know about NP-complete problems because some of them arise surprisinglyoften in real applications. If you are called upon to produce an efficient algorithm for an NP-complete problem, you are likely to spend a lot of time in a fruitless search. If you can show
  • 14. that the problem is NP-complete, you can instead spend your time developing an efficientalgorithm that gives a good, but not the best possible, solution.As a concrete example, consider a trucking company with a central warehouse. Each day, itloads up the truck at the warehouse and sends it around to several locations to makedeliveries. At the end of the day, the truck must end up back at the warehouse so that it isready to be loaded for the next day. To reduce costs, the company wants to select an order ofdelivery stops that yields the lowest overall distance traveled by the truck. This problem is thewell-known "traveling-salesman problem," and it is NP-complete. It has no known efficientalgorithm. Under certain assumptions, however, there are efficient algorithms that give anoverall distance that is not too far above the smallest possible. Chapter 35 discusses such"approximation algorithms."Exercises 1.1-1Give a real-world example in which one of the following computational problems appears:sorting, determining the best order for multiplying matrices, or finding the convex hull.Exercises 1.1-2Other than speed, what other measures of efficiency might one use in a real-world setting?Exercises 1.1-3Select a data structure that you have seen previously, and discuss its strengths and limitations.Exercises 1.1-4How are the shortest-path and traveling-salesman problems given above similar? How arethey different?Exercises 1.1-5Come up with a real-world problem in which only the best solution will do. Then come upwith one in which a solution that is "approximately" the best is good enough.1.2 Algorithms as a technology
  • 15. Suppose computers were infinitely fast and computer memory was free. Would you have anyreason to study algorithms? The answer is yes, if for no other reason than that you would stilllike to demonstrate that your solution method terminates and does so with the correct answer.If computers were infinitely fast, any correct method for solving a problem would do. Youwould probably want your implementation to be within the bounds of good softwareengineering practice (i.e., well designed and documented), but you would most often usewhichever method was the easiest to implement.Of course, computers may be fast, but they are not infinitely fast. And memory may be cheap,but it is not free. Computing time is therefore a bounded resource, and so is space in memory.These resources should be used wisely, and algorithms that are efficient in terms of time orspace will help you do so.EfficiencyAlgorithms devised to solve the same problem often differ dramatically in their efficiency.These differences can be much more significant than differences due to hardware andsoftware.As an example, in Chapter 2, we will see two algorithms for sorting. The first, known asinsertion sort, takes time roughly equal to c1n2 to sort n items, where c1 is a constant that doesnot depend on n. That is, it takes time roughly proportional to n2. The second, merge sort,takes time roughly equal to c2n lg n, where lg n stands for log2 n and c2 is another constantthat also does not depend on n. Insertion sort usually has a smaller constant factor than mergesort, so that c1 < c2. We shall see that the constant factors can be far less significant in therunning time than the dependence on the input size n. Where merge sort has a factor of lg n inits running time, insertion sort has a factor of n, which is much larger. Although insertion sortis usually faster than merge sort for small input sizes, once the input size n becomes largeenough, merge sorts advantage of lg n vs. n will more than compensate for the difference inconstant factors. No matter how much smaller c1 is than c2, there will always be a crossoverpoint beyond which merge sort is faster.For a concrete example, let us pit a faster computer (computer A) running insertion sortagainst a slower computer (computer B) running merge sort. They each must sort an array ofone million numbers. Suppose that computer A executes one billion instructions per secondand computer B executes only ten million instructions per second, so that computer A is 100times faster than computer B in raw computing power. To make the difference even moredramatic, suppose that the worlds craftiest programmer codes insertion sort in machinelanguage for computer A, and the resulting code requires 2n2 instructions to sort n numbers.(Here, c1 = 2.) Merge sort, on the other hand, is programmed for computer B by an averageprogrammer using a high-level language with an inefficient compiler, with the resulting codetaking 50n lg n instructions (so that c2 = 50). To sort one million numbers, computer A takeswhile computer B takes
  • 16. By using an algorithm whose running time grows more slowly, even with a poor compiler,computer B runs 20 times faster than computer A! The advantage of merge sort is even morepronounced when we sort ten million numbers: where insertion sort takes approximately 2.3days, merge sort takes under 20 minutes. In general, as the problem size increases, so does therelative advantage of merge sort.Algorithms and other technologiesThe example above shows that algorithms, like computer hardware, are a technology. Totalsystem performance depends on choosing efficient algorithms as much as on choosing fasthardware. Just as rapid advances are being made in other computer technologies, they arebeing made in algorithms as well.You might wonder whether algorithms are truly that important on contemporary computers inlight of other advanced technologies, such as • hardware with high clock rates, pipelining, and superscalar architectures, • easy-to-use, intuitive graphical user interfaces (GUIs), • object-oriented systems, and • local-area and wide-area networking.The answer is yes. Although there are some applications that do not explicitly requirealgorithmic content at the application level (e.g., some simple web-based applications), mostalso require a degree of algorithmic content on their own. For example, consider a web-basedservice that determines how to travel from one location to another. (Several such servicesexisted at the time of this writing.) Its implementation would rely on fast hardware, agraphical user interface, wide-area networking, and also possibly on object orientation.However, it would also require algorithms for certain operations, such as finding routes(probably using a shortest-path algorithm), rendering maps, and interpolating addresses.Moreover, even an application that does not require algorithmic content at the applicationlevel relies heavily upon algorithms. Does the application rely on fast hardware? Thehardware design used algorithms. Does the application rely on graphical user interfaces? Thedesign of any GUI relies on algorithms. Does the application rely on networking? Routing innetworks relies heavily on algorithms. Was the application written in a language other thanmachine code? Then it was processed by a compiler, interpreter, or assembler, all of whichmake extensive use of algorithms. Algorithms are at the core of most technologies used incontemporary computers.Furthermore, with the ever-increasing capacities of computers, we use them to solve largerproblems than ever before. As we saw in the above comparison between insertion sort andmerge sort, it is at larger problem sizes that the differences in efficiencies between algorithmsbecome particularly prominent.Having a solid base of algorithmic knowledge and technique is one characteristic thatseparates the truly skilled programmers from the novices. With modern computing
  • 17. technology, you can accomplish some tasks without knowing much about algorithms, butwith a good background in algorithms, you can do much, much more.Exercises 1.2-1Give an example of an application that requires algorithmic content at the application level,and discuss the function of the algorithms involved.Exercises 1.2-2Suppose we are comparing implementations of insertion sort and merge sort on the samemachine. For inputs of size n, insertion sort runs in 8n2 steps, while merge sort runs in 64n lgn steps. For which values of n does insertion sort beat merge sort?Exercises 1.2-3What is the smallest value of n such that an algorithm whose running time is 100n2 runs fasterthan an algorithm whose running time is 2n on the same machine?Problems 1-1: Comparison of running timesFor each function f(n) and time t in the following table, determine the largest size n of aproblem that can be solved in time t, assuming that the algorithm to solve the problem takesf(n) microseconds. 1 1 1 1 1 1 1 second minute hour day month year centurylg n nn lg n n2 n3 2n n!
  • 18. Chapter notesThere are many excellent texts on the general topic of algorithms, including those by Aho,Hopcroft, and Ullman [5, 6], Baase and Van Gelder [26], Brassard and Bratley [46, 47],Goodrich and Tamassia [128], Horowitz, Sahni, and Rajasekaran [158], Kingston [179],Knuth [182, 183, 185], Kozen [193], Manber [210], Mehlhorn [217, 218, 219], Purdom andBrown [252], Reingold, Nievergelt, and Deo [257], Sedgewick [269], Skiena [280], and Wilf[315]. Some of the more practical aspects of algorithm design are discussed by Bentley [39,40] and Gonnet [126]. Surveys of the field of algorithms can also be found in the Handbookof Theoretical Computer Science, Volume A [302] and the CRC Handbook on Algorithmsand Theory of Computation [24]. Overviews of the algorithms used in computational biologycan be found in textbooks by Gusfield [136], Pevzner [240], Setubal and Medinas [272], andWaterman [309].Chapter 2: Getting StartedThis chapter will familiarize you with the framework we shall use throughout the book tothink about the design and analysis of algorithms. It is self-contained, but it does includeseveral references to material that will be introduced in Chapters 3 and 4. (It also containsseveral summations, which Appendix A shows how to solve.)We begin by examining the insertion sort algorithm to solve the sorting problem introduced inChapter 1. We define a "pseudocode" that should be familiar to readers who have donecomputer programming and use it to show how we shall specify our algorithms. Havingspecified the algorithm, we then argue that it correctly sorts and we analyze its running time.The analysis introduces a notation that focuses on how that time increases with the number ofitems to be sorted. Following our discussion of insertion sort, we introduce the divide-and-conquer approach to the design of algorithms and use it to develop an algorithm called mergesort. We end with an analysis of merge sorts running time.2.1 Insertion sortOur first algorithm, insertion sort, solves the sorting problem introduced in Chapter 1: • Input: A sequence of n numbers a1, a2, . . .,an . • Output: A permutation (reordering) of the input sequence such that .The numbers that we wish to sort are also known as the keys.In this book, we shall typically describe algorithms as programs written in a pseudocode thatis similar in many respects to C, Pascal, or Java. If you have been introduced to any of theselanguages, you should have little trouble reading our algorithms. What separates pseudocodefrom "real" code is that in pseudocode, we employ whatever expressive method is most clearand concise to specify a given algorithm. Sometimes, the clearest method is English, so do notbe surprised if you come across an English phrase or sentence embedded within a section of"real" code. Another difference between pseudocode and real code is that pseudocode is nottypically concerned with issues of software engineering. Issues of data abstraction,
  • 19. modularity, and error handling are often ignored in order to convey the essence of thealgorithm more concisely.We start with insertion sort, which is an efficient algorithm for sorting a small number ofelements. Insertion sort works the way many people sort a hand of playing cards. We startwith an empty left hand and the cards face down on the table. We then remove one card at atime from the table and insert it into the correct position in the left hand. To find the correctposition for a card, we compare it with each of the cards already in the hand, from right toleft, as illustrated in Figure 2.1. At all times, the cards held in the left hand are sorted, andthese cards were originally the top cards of the pile on the table.Figure 2.1: Sorting a hand of cards using insertion sort.Our pseudocode for insertion sort is presented as a procedure called INSERTION-SORT,which takes as a parameter an array A[1 n] containing a sequence of length n that is to besorted. (In the code, the number n of elements in A is denoted by length[A].) The inputnumbers are sorted in place: the numbers are rearranged within the array A, with at most aconstant number of them stored outside the array at any time. The input array A contains thesorted output sequence when INSERTION-SORT is finished.INSERTION-SORT(A)1 for j ← 2 to length[A]2 do key ← A[j]3 ▹ Insert A[j] into the sorted sequence A[1 j - 1].4 i ← j - 15 while i > 0 and A[i] > key6 do A[i + 1] ← A[i]7 i ← i - 18 A[i + 1] ← keyLoop invariants and the correctness of insertion sortFigure 2.2 shows how this algorithm works for A = 5, 2, 4, 6, 1, 3 . The index j indicatesthe "current card" being inserted into the hand. At the beginning of each iteration of the"outer" for loop, which is indexed by j, the subarray consisting of elements A[1 j - 1]constitute the currently sorted hand, and elements A[j + 1 n] correspond to the pile of cardsstill on the table. In fact, elements A[1 j - 1] are the elements originally in positions 1through j - 1, but now in sorted order. We state these properties of A[1 j -1] formally as aloop invariant:
  • 20. • At the start of each iteration of the for loop of lines 1-8, the subarray A[1 j - 1] consists of the elements originally in A[1 j - 1] but in sorted order.Figure 2.2: The operation of INSERTION-SORT on the array A = 5, 2, 4, 6, 1, 3 . Arrayindices appear above the rectangles, and values stored in the array positions appear within therectangles. (a)-(e) The iterations of the for loop of lines 1-8. In each iteration, the blackrectangle holds the key taken from A[j], which is compared with the values in shadedrectangles to its left in the test of line 5. Shaded arrows show array values moved one positionto the right in line 6, and black arrows indicate where the key is moved to in line 8. (f) Thefinal sorted array.We use loop invariants to help us understand why an algorithm is correct. We must showthree things about a loop invariant: • Initialization: It is true prior to the first iteration of the loop. • Maintenance: If it is true before an iteration of the loop, it remains true before the next iteration. • Termination: When the loop terminates, the invariant gives us a useful property that helps show that the algorithm is correct.When the first two properties hold, the loop invariant is true prior to every iteration of theloop. Note the similarity to mathematical induction, where to prove that a property holds, youprove a base case and an inductive step. Here, showing that the invariant holds before the firstiteration is like the base case, and showing that the invariant holds from iteration to iteration islike the inductive step.The third property is perhaps the most important one, since we are using the loop invariant toshow correctness. It also differs from the usual use of mathematical induction, in which theinductive step is used infinitely; here, we stop the "induction" when the loop terminates.Let us see how these properties hold for insertion sort. • Initialization: We start by showing that the loop invariant holds before the first loop iteration, when j = 2.[1] The subarray A[1 j - 1], therefore, consists of just the single element A[1], which is in fact the original element in A[1]. Moreover, this subarray is sorted (trivially, of course), which shows that the loop invariant holds prior to the first iteration of the loop. • Maintenance: Next, we tackle the second property: showing that each iteration maintains the loop invariant. Informally, the body of the outer for loop works by moving A[ j - 1], A[ j - 2], A[ j - 3], and so on by one position to the right until the proper position for A[ j] is found (lines 4-7), at which point the value of A[j] is inserted (line 8). A more formal treatment of the second property would require us to state and show a loop invariant for the "inner" while loop. At this point, however, we prefer not to get bogged down in such formalism, and so we rely on our informal analysis to show that the second property holds for the outer loop.
  • 21. • Termination: Finally, we examine what happens when the loop terminates. For insertion sort, the outer for loop ends when j exceeds n, i.e., when j = n + 1. Substituting n + 1 for j in the wording of loop invariant, we have that the subarray A[1 n] consists of the elements originally in A[1 n], but in sorted order. But the subarray A[1 n] is the entire array! Hence, the entire array is sorted, which means that the algorithm is correct.We shall use this method of loop invariants to show correctness later in this chapter and inother chapters as well.Pseudocode conventionsWe use the following conventions in our pseudocode. 1. Indentation indicates block structure. For example, the body of the for loop that begins on line 1 consists of lines 2-8, and the body of the while loop that begins on line 5 contains lines 6-7 but not line 8. Our indentation style applies to if-then-else statements as well. Using indentation instead of conventional indicators of block structure, such as begin and end statements, greatly reduces clutter while preserving, or even enhancing, clarity.[2] 2. The looping constructs while, for, and repeat and the conditional constructs if, then, and else have interpretations similar to those in Pascal.[3] There is one subtle difference with respect to for loops, however: in Pascal, the value of the loop-counter variable is undefined upon exiting the loop, but in this book, the loop counter retains its value after exiting the loop. Thus, immediately after a for loop, the loop counters value is the value that first exceeded the for loop bound. We used this property in our correctness argument for insertion sort. The for loop header in line 1 is for j ← 2 to length[A], and so when this loop terminates, j = length[A]+1 (or, equivalently, j = n+1, since n = length[A]). 3. The symbol "▹" indicates that the remainder of the line is a comment. 4. A multiple assignment of the form i ← j ← e assigns to both variables i and j the value of expression e; it should be treated as equivalent to the assignment j ← e followed by the assignment i ← j. 5. Variables (such as i, j, and key) are local to the given procedure. We shall not use global variables without explicit indication. 6. Array elements are accessed by specifying the array name followed by the index in square brackets. For example, A[i] indicates the ith element of the array A. The notation " " is used to indicate a range of values within an array. Thus, A[1 j] indicates the subarray of A consisting of the j elements A[1], A[2], . . . , A[j]. 7. Compound data are typically organized into objects, which are composed of attributes or fields. A particular field is accessed using the field name followed by the name of its object in square brackets. For example, we treat an array as an object with the attribute length indicating how many elements it contains. To specify the number of elements in an array A, we write length[A]. Although we use square brackets for both array indexing and object attributes, it will usually be clear from the context which interpretation is intended. A variable representing an array or object is treated as a pointer to the data representing the array or object. For all fields f of an object x, setting y ← x causes f[y] = f[x]. Moreover, if we now set f[x] ← 3, then afterward not only is f[x] = 3, but f[y] =
  • 22. 3 as well. In other words, x and y point to ("are") the same object after the assignment y ← x. Sometimes, a pointer will refer to no object at all. In this case, we give it the special value NIL. 8. Parameters are passed to a procedure by value: the called procedure receives its own copy of the parameters, and if it assigns a value to a parameter, the change is not seen by the calling procedure. When objects are passed, the pointer to the data representing the object is copied, but the objects fields are not. For example, if x is a parameter of a called procedure, the assignment x ← y within the called procedure is not visible to the calling procedure. The assignment f [x] ← 3, however, is visible. 9. The boolean operators "and" and "or" are short circuiting. That is, when we evaluate the expression "x and y" we first evaluate x. If x evaluates to FALSE, then the entire expression cannot evaluate to TRUE, and so we do not evaluate y. If, on the other hand, x evaluates to TRUE, we must evaluate y to determine the value of the entire expression. Similarly, in the expression "x or y" we evaluate the expression y only if x evaluates to FALSE. Short-circuiting operators allow us to write boolean expressions such as "x ≠ NIL and f[x] = y" without worrying about what happens when we try to evaluate f[x] when x is NIL.Exercises 2.1-1Using Figure 2.2 as a model, illustrate the operation of INSERTION-SORT on the array A = 31, 41, 59, 26, 41, 58 .Exercises 2.1-2Rewrite the INSERTION-SORT procedure to sort into nonincreasing instead ofnondecreasing order.Exercises 2.1-3Consider the searching problem: • Input: A sequence of n numbers A = a1, a2, . . . , an and a value v. • Output: An index i such that v = A[i] or the special value NIL if v does not appear in A.Write pseudocode for linear search, which scans through the sequence, looking for v. Using aloop invariant, prove that your algorithm is correct. Make sure that your loop invariant fulfillsthe three necessary properties.
  • 23. Exercises 2.1-4Consider the problem of adding two n-bit binary integers, stored in two n-element arrays Aand B. The sum of the two integers should be stored in binary form in an (n + 1)-elementarray C. State the problem formally and write pseudocode for adding the two integers.[1] When the loop is a for loop, the moment at which we check the loop invariant just prior tothe first iteration is immediately after the initial assignment to the loop-counter variable andjust before the first test in the loop header. In the case of INSERTION-SORT, this time isafter assigning 2 to the variable j but before the first test of whether j ≤ length[A].[2] In real programming languages, it is generally not advisable to use indentation alone toindicate block structure, since levels of indentation are hard to determine when code is splitacross pages.[3] Most block-structured languages have equivalent constructs, though the exact syntax maydiffer from that of Pascal.2.2 Analyzing algorithmsAnalyzing an algorithm has come to mean predicting the resources that the algorithmrequires. Occasionally, resources such as memory, communication bandwidth, or computerhardware are of primary concern, but most often it is computational time that we want tomeasure. Generally, by analyzing several candidate algorithms for a problem, a most efficientone can be easily identified. Such analysis may indicate more than one viable candidate, butseveral inferior algorithms are usually discarded in the process.Before we can analyze an algorithm, we must have a model of the implementation technologythat will be used, including a model for the resources of that technology and their costs. Formost of this book, we shall assume a generic one-processor, random-access machine (RAM)model of computation as our implementation technology and understand that our algorithmswill be implemented as computer programs. In the RAM model, instructions are executed oneafter another, with no concurrent operations. In later chapters, however, we shall haveoccasion to investigate models for digital hardware.Strictly speaking, one should precisely define the instructions of the RAM model and theircosts. To do so, however, would be tedious and would yield little insight into algorithmdesign and analysis. Yet we must be careful not to abuse the RAM model. For example, whatif a RAM had an instruction that sorts? Then we could sort in just one instruction. Such aRAM would be unrealistic, since real computers do not have such instructions. Our guide,therefore, is how real computers are designed. The RAM model contains instructionscommonly found in real computers: arithmetic (add, subtract, multiply, divide, remainder,floor, ceiling), data movement (load, store, copy), and control (conditional and unconditionalbranch, subroutine call and return). Each such instruction takes a constant amount of time.
  • 24. The data types in the RAM model are integer and floating point. Although we typically do notconcern ourselves with precision in this book, in some applications precision is crucial. Wealso assume a limit on the size of each word of data. For example, when working with inputsof size n, we typically assume that integers are represented by c lg n bits for some constant c ≥1. We require c ≥ 1 so that each word can hold the value of n, enabling us to index theindividual input elements, and we restrict c to be a constant so that the word size does notgrow arbitrarily. (If the word size could grow arbitrarily, we could store huge amounts of datain one word and operate on it all in constant time-clearly an unrealistic scenario.)Real computers contain instructions not listed above, and such instructions represent a grayarea in the RAM model. For example, is exponentiation a constant-time instruction? In thegeneral case, no; it takes several instructions to compute xy when x and y are real numbers. Inrestricted situations, however, exponentiation is a constant-time operation. Many computershave a "shift left" instruction, which in constant time shifts the bits of an integer by kpositions to the left. In most computers, shifting the bits of an integer by one position to theleft is equivalent to multiplication by 2. Shifting the bits by k positions to the left is equivalentto multiplication by 2k. Therefore, such computers can compute 2k in one constant-timeinstruction by shifting the integer 1 by k positions to the left, as long as k is no more than thenumber of bits in a computer word. We will endeavor to avoid such gray areas in the RAMmodel, but we will treat computation of 2k as a constant-time operation when k is a smallenough positive integer.In the RAM model, we do not attempt to model the memory hierarchy that is common incontemporary computers. That is, we do not model caches or virtual memory (which is mostoften implemented with demand paging). Several computational models attempt to accountfor memory-hierarchy effects, which are sometimes significant in real programs on realmachines. A handful of problems in this book examine memory-hierarchy effects, but for themost part, the analyses in this book will not consider them. Models that include the memoryhierarchy are quite a bit more complex than the RAM model, so that they can be difficult towork with. Moreover, RAM-model analyses are usually excellent predictors of performanceon actual machines.Analyzing even a simple algorithm in the RAM model can be a challenge. The mathematicaltools required may include combinatorics, probability theory, algebraic dexterity, and theability to identify the most significant terms in a formula. Because the behavior of analgorithm may be different for each possible input, we need a means for summarizing thatbehavior in simple, easily understood formulas.Even though we typically select only one machine model to analyze a given algorithm, westill face many choices in deciding how to express our analysis. We would like a way that issimple to write and manipulate, shows the important characteristics of an algorithms resourcerequirements, and suppresses tedious details.Analysis of insertion sortThe time taken by the INSERTION-SORT procedure depends on the input: sorting a thousandnumbers takes longer than sorting three numbers. Moreover, INSERTION-SORT can takedifferent amounts of time to sort two input sequences of the same size depending on hownearly sorted they already are. In general, the time taken by an algorithm grows with the sizeof the input, so it is traditional to describe the running time of a program as a function of the
  • 25. size of its input. To do so, we need to define the terms "running time" and "size of input"more carefully.The best notion for input size depends on the problem being studied. For many problems,such as sorting or computing discrete Fourier transforms, the most natural measure is thenumber of items in the input-for example, the array size n for sorting. For many otherproblems, such as multiplying two integers, the best measure of input size is the total numberof bits needed to represent the input in ordinary binary notation. Sometimes, it is moreappropriate to describe the size of the input with two numbers rather than one. For instance, ifthe input to an algorithm is a graph, the input size can be described by the numbers of verticesand edges in the graph. We shall indicate which input size measure is being used with eachproblem we study.The running time of an algorithm on a particular input is the number of primitive operationsor "steps" executed. It is convenient to define the notion of step so that it is as machine-independent as possible. For the moment, let us adopt the following view. A constant amountof time is required to execute each line of our pseudocode. One line may take a differentamount of time than another line, but we shall assume that each execution of the ith line takestime ci , where ci is a constant. This viewpoint is in keeping with the RAM model, and it alsoreflects how the pseudocode would be implemented on most actual computers.[4]In the following discussion, our expression for the running time of INSERTION-SORT willevolve from a messy formula that uses all the statement costs ci to a much simpler notationthat is more concise and more easily manipulated. This simpler notation will also make it easyto determine whether one algorithm is more efficient than another.We start by presenting the INSERTION-SORT procedure with the time "cost" of eachstatement and the number of times each statement is executed. For each j = 2, 3, . . . , n, wheren = length[A], we let tj be the number of times the while loop test in line 5 is executed for thatvalue of j. When a for or while loop exits in the usual way (i.e., due to the test in the loopheader), the test is executed one time more than the loop body. We assume that comments arenot executable statements, and so they take no time.INSERTION-SORT(A) cost times1 for j ← 2 to length[A] c1 n2 do key ← A[j] c2 n - 13 ▹ Insert A[j] into the sorted sequence A[1 j - 1]. 0 n - 14 i ← j - 1 c4 n - 15 while i > 0 and A[i] > key c56 do A[i + 1] ← A[i] c67 i ← i - 1 c78 A[i + 1] ← key c8 n - 1The running time of the algorithm is the sum of running times for each statement executed; astatement that takes ci steps to execute and is executed n times will contribute cin to the totalrunning time.[5] To compute T(n), the running time of INSERTION-SORT, we sum theproducts of the cost and times columns, obtaining
  • 26. Even for inputs of a given size, an algorithms running time may depend on which input ofthat size is given. For example, in INSERTION-SORT, the best case occurs if the array isalready sorted. For each j = 2, 3, . . . , n, we then find that A[i] ≤ key in line 5 when i has itsinitial value of j - 1. Thus tj = 1 for j = 2, 3, . . . , n, and the best-case running time isT(n) = c1n + c2(n - 1) + c4(n - 1) + c5(n - 1) + c8(n - 1) = (c1 + c2 + c4 + c5 + c8)n - (c2+ c4 + c5 + c8).This running time can be expressed as an + b for constants a and b that depend on thestatement costs ci ; it is thus a linear function of n.If the array is in reverse sorted order-that is, in decreasing order-the worst case results. Wemust compare each element A[j] with each element in the entire sorted subarray A[1 j - 1],and so tj = j for j = 2, 3, . . . , n. Noting thatand(see Appendix A for a review of how to solve these summations), we find that in the worstcase, the running time of INSERTION-SORT isThis worst-case running time can be expressed as an2 + bn + c for constants a, b, and c thatagain depend on the statement costs ci ; it is thus a quadratic function of n.Typically, as in insertion sort, the running time of an algorithm is fixed for a given input,although in later chapters we shall see some interesting "randomized" algorithms whosebehavior can vary even for a fixed input.Worst-case and average-case analysis
  • 27. In our analysis of insertion sort, we looked at both the best case, in which the input array wasalready sorted, and the worst case, in which the input array was reverse sorted. For theremainder of this book, though, we shall usually concentrate on finding only the worst-caserunning time, that is, the longest running time for any input of size n. We give three reasonsfor this orientation. • The worst-case running time of an algorithm is an upper bound on the running time for any input. Knowing it gives us a guarantee that the algorithm will never take any longer. We need not make some educated guess about the running time and hope that it never gets much worse. • For some algorithms, the worst case occurs fairly often. For example, in searching a database for a particular piece of information, the searching algorithms worst case will often occur when the information is not present in the database. In some searching applications, searches for absent information may be frequent. • The "average case" is often roughly as bad as the worst case. Suppose that we randomly choose n numbers and apply insertion sort. How long does it take to determine where in subarray A[1 j - 1] to insert element A[j]? On average, half the elements in A[1 j - 1] are less than A[j], and half the elements are greater. On average, therefore, we check half of the subarray A[1 j - 1], so tj = j/2. If we work out the resulting average-case running time, it turns out to be a quadratic function of the input size, just like the worst-case running time.In some particular cases, we shall be interested in the average-case or expected running timeof an algorithm; in Chapter 5, we shall see the technique of probabilistic analysis, by whichwe determine expected running times. One problem with performing an average-caseanalysis, however, is that it may not be apparent what constitutes an "average" input for aparticular problem. Often, we shall assume that all inputs of a given size are equally likely. Inpractice, this assumption may be violated, but we can sometimes use a randomizedalgorithm, which makes random choices, to allow a probabilistic analysis.Order of growthWe used some simplifying abstractions to ease our analysis of the INSERTION-SORTprocedure. First, we ignored the actual cost of each statement, using the constants ci torepresent these costs. Then, we observed that even these constants give us more detail than wereally need: the worst-case running time is an2 + bn + c for some constants a, b, and c thatdepend on the statement costs ci. We thus ignored not only the actual statement costs, but alsothe abstract costs ci.We shall now make one more simplifying abstraction. It is the rate of growth, or order ofgrowth, of the running time that really interests us. We therefore consider only the leadingterm of a formula (e.g., an2), since the lower-order terms are relatively insignificant for largen. We also ignore the leading terms constant coefficient, since constant factors are lesssignificant than the rate of growth in determining computational efficiency for large inputs.Thus, we write that insertion sort, for example, has a worst-case running time of Θ(n2)(pronounced "theta of n-squared"). We shall use Θ-notation informally in this chapter; it willbe defined precisely in Chapter 3.We usually consider one algorithm to be more efficient than another if its worst-case runningtime has a lower order of growth. Due to constant factors and lower-order terms, this
  • 28. evaluation may be in error for small inputs. But for large enough inputs, a Θ(n2) algorithm, forexample, will run more quickly in the worst case than a Θ(n3) algorithm.Exercises 2.2-1Express the function n3/1000 - 100n2 - 100n + 3 in terms of Θ-notation.Exercises 2.2-2Consider sorting n numbers stored in array A by first finding the smallest element of A andexchanging it with the element in A[1]. Then find the second smallest element of A, andexchange it with A[2]. Continue in this manner for the first n - 1 elements of A. Writepseudocode for this algorithm, which is known as selection sort. What loop invariant doesthis algorithm maintain? Why does it need to run for only the first n - 1 elements, rather thanfor all n elements? Give the best-case and worst-case running times of selection sort in Θ-notation.Exercises 2.2-3Consider linear search again (see Exercise 2.1-3). How many elements of the input sequenceneed to be checked on the average, assuming that the element being searched for is equallylikely to be any element in the array? How about in the worst case? What are the average-caseand worst-case running times of linear search in Θ-notation? Justify your answers.Exercises 2.2-4How can we modify almost any algorithm to have a good best-case running time?[4] There are some subtleties here. Computational steps that we specify in English are oftenvariants of a procedure that requires more than just a constant amount of time. For example,later in this book we might say "sort the points by x-coordinate," which, as we shall see, takesmore than a constant amount of time. Also, note that a statement that calls a subroutine takesconstant time, though the subroutine, once invoked, may take more. That is, we separate theprocess of calling the subroutine-passing parameters to it, etc.-from the process of executingthe subroutine.
  • 29. [5] This characteristic does not necessarily hold for a resource such as memory. A statementthat references m words of memory and is executed n times does not necessarily consume mnwords of memory in total.2.3 Designing algorithmsThere are many ways to design algorithms. Insertion sort uses an incremental approach:having sorted the subarray A[1 j - 1], we insert the single element A[j] into its proper place,yielding the sorted subarray A[1 j].In this section, we examine an alternative design approach, known as "divide-and-conquer."We shall use divide-and-conquer to design a sorting algorithm whose worst-case running timeis much less than that of insertion sort. One advantage of divide-and-conquer algorithms isthat their running times are often easily determined using techniques that will be introduced inChapter 4.2.3.1 The divide-and-conquer approachMany useful algorithms are recursive in structure: to solve a given problem, they callthemselves recursively one or more times to deal with closely related subproblems. Thesealgorithms typically follow a divide-and-conquer approach: they break the problem intoseveral subproblems that are similar to the original problem but smaller in size, solve thesubproblems recursively, and then combine these solutions to create a solution to the originalproblem.The divide-and-conquer paradigm involves three steps at each level of the recursion: • Divide the problem into a number of subproblems. • Conquer the subproblems by solving them recursively. If the subproblem sizes are small enough, however, just solve the subproblems in a straightforward manner. • Combine the solutions to the subproblems into the solution for the original problem.The merge sort algorithm closely follows the divide-and-conquer paradigm. Intuitively, itoperates as follows. • Divide: Divide the n-element sequence to be sorted into two subsequences of n/2 elements each. • Conquer: Sort the two subsequences recursively using merge sort. • Combine: Merge the two sorted subsequences to produce the sorted answer.The recursion "bottoms out" when the sequence to be sorted has length 1, in which case thereis no work to be done, since every sequence of length 1 is already in sorted order.The key operation of the merge sort algorithm is the merging of two sorted sequences in the"combine" step. To perform the merging, we use an auxiliary procedure MERGE(A, p, q, r),where A is an array and p, q, and r are indices numbering elements of the array such that p ≤ q< r. The procedure assumes that the subarrays A[p q] and A[q + 1 r] are in sorted order.It merges them to form a single sorted subarray that replaces the current subarray A[p r].
  • 30. Our MERGE procedure takes time Θ(n), where n = r - p + 1 is the number of elements beingmerged, and it works as follows. Returning to our card-playing motif, suppose we have twopiles of cards face up on a table. Each pile is sorted, with the smallest cards on top. We wishto merge the two piles into a single sorted output pile, which is to be face down on the table.Our basic step consists of choosing the smaller of the two cards on top of the face-up piles,removing it from its pile (which exposes a new top card), and placing this card face downonto the output pile. We repeat this step until one input pile is empty, at which time we justtake the remaining input pile and place it face down onto the output pile. Computationally,each basic step takes constant time, since we are checking just two top cards. Since weperform at most n basic steps, merging takes Θ(n) time.The following pseudocode implements the above idea, but with an additional twist that avoidshaving to check whether either pile is empty in each basic step. The idea is to put on thebottom of each pile a sentinel card, which contains a special value that we use to simplify ourcode. Here, we use ∞ as the sentinel value, so that whenever a card with ∞ is exposed, itcannot be the smaller card unless both piles have their sentinel cards exposed. But once thathappens, all the nonsentinel cards have already been placed onto the output pile. Since weknow in advance that exactly r - p + 1 cards will be placed onto the output pile, we can stoponce we have performed that many basic steps.MERGE(A, p, q, r) 1 n1 ← q - p + 1 2 n2 ← r - q 3 create arrays L[1 n1 + 1] and R[1 n2 + 1] 4 for i ← 1 to n1 5 do L[i] ← A[p + i - 1] 6 for j ← 1 to n2 7 do R[j] ← A[q + j] 8 L[n1 + 1] ← ∞ 9 R[n2 + 1] ← ∞10 i ← 111 j ← 112 for k ← p to r13 do if L[i] ≤ R[j]14 then A[k] ← L[i]15 i ← i + 116 else A[k] ← R[j]17 j ← j + 1In detail, the MERGE procedure works as follows. Line 1 computes the length n1 of thesubarray A[p q], and line 2 computes the length n2 of the subarray A[q + 1 r]. We createarrays L and R ("left" and "right"), of lengths n1 + 1 and n2 + 1, respectively, in line 3. The forloop of lines 4-5 copies the subarray A[p q] into L[1 n1], and the for loop of lines 6-7copies the subarray A[q + 1 r] into R[1 n2]. Lines 8-9 put the sentinels at the ends of thearrays L and R. Lines 10-17, illustrated in Figure 2.3, perform the r - p + 1 basic steps bymaintaining the following loop invariant: • At the start of each iteration of the for loop of lines 12-17, the subarray A[p k - 1] contains the k - p smallest elements of L[1 n1 + 1] and R[1 n2 + 1], in sorted order. Moreover, L[i] and R[j] are the smallest elements of their arrays that have not been copied back into A.
  • 31. Figure 2.3: The operation of lines 10-17 in the call MERGE(A, 9, 12, 16), when the subarrayA[9 16] contains the sequence 2, 4, 5, 7, 1, 2, 3, 6 . After copying and insertingsentinels, the array L contains 2, 4, 5, 7, ∞ , and the array R contains 1, 2, 3, 6, ∞ .Lightly shaded positions in A contain their final values, and lightly shaded positions in L andR contain values that have yet to be copied back into A. Taken together, the lightly shadedpositions always comprise the values originally in A[9 16], along with the two sentinels.Heavily shaded positions in A contain values that will be copied over, and heavily shadedpositions in L and R contain values that have already been copied back into A. (a)-(h) Thearrays A, L, and R, and their respective indices k, i, and j prior to each iteration of the loop oflines 12-17. (i) The arrays and indices at termination. At this point, the subarray in A[9 16]is sorted, and the two sentinels in L and R are the only two elements in these arrays that havenot been copied into A.We must show that this loop invariant holds prior to the first iteration of the for loop of lines12-17, that each iteration of the loop maintains the invariant, and that the invariant provides auseful property to show correctness when the loop terminates. • Initialization: Prior to the first iteration of the loop, we have k = p, so that the subarray A[p k - 1] is empty. This empty subarray contains the k - p = 0 smallest elements of L and R, and since i = j = 1, both L[i] and R[j] are the smallest elements of their arrays that have not been copied back into A. • Maintenance: To see that each iteration maintains the loop invariant, let us first suppose that L[i] ≤ R[j]. Then L[i] is the smallest element not yet copied back into A. Because A[p k - 1] contains the k - p smallest elements, after line 14 copies L[i] into A[k], the subarray A[p k] will contain the k - p + 1 smallest elements. Incrementing k (in the for loop update) and i (in line 15) reestablishes the loop invariant for the next
  • 32. iteration. If instead L[i] > R[j], then lines 16-17 perform the appropriate action to maintain the loop invariant. • Termination: At termination, k = r + 1. By the loop invariant, the subarray A[p k - 1], which is A[p r], contains the k - p = r - p + 1 smallest elements of L[1 n1 + 1] and R[1 n2 + 1], in sorted order. The arrays L and R together contain n1 + n2 + 2 = r - p + 3 elements. All but the two largest have been copied back into A, and these two largest elements are the sentinels.To see that the MERGE procedure runs in Θ(n) time, where n = r - p + 1, observe that each oflines 1-3 and 8-11 takes constant time, the for loops of lines 4-7 take Θ(n1 + n2) = Θ(n)time,[6] and there are n iterations of the for loop of lines 12-17, each of which takes constanttime.We can now use the MERGE procedure as a subroutine in the merge sort algorithm. Theprocedure MERGE-SORT(A, p, r) sorts the elements in the subarray A[p r]. If p ≥ r, thesubarray has at most one element and is therefore already sorted. Otherwise, the divide stepsimply computes an index q that partitions A[p r] into two subarrays: A[p q], containing⌈n/2⌉ elements, and A[q + 1 r], containing ⌊n/2⌋ elements.[7]MERGE-SORT(A, p, r)1 if p < r2 then q ← ⌊(p + r)/2⌋3 MERGE-SORT(A, p, q)4 MERGE-SORT(A, q + 1, r)5 MERGE(A, p, q, r)To sort the entire sequence A = A[1], A[2], . . . , A[n] , we make the initial call MERGE-SORT(A, 1, length[A]), where once again length[A] = n. Figure 2.4 illustrates the operation ofthe procedure bottom-up when n is a power of 2. The algorithm consists of merging pairs of1-item sequences to form sorted sequences of length 2, merging pairs of sequences of length 2to form sorted sequences of length 4, and so on, until two sequences of length n/2 are mergedto form the final sorted sequence of length n.Figure 2.4: The operation of merge sort on the array A = 5, 2, 4, 7, 1, 3, 2, 6 . The lengthsof the sorted sequences being merged increase as the algorithm progresses from bottom to top.2.3.2 Analyzing divide-and-conquer algorithms
  • 33. When an algorithm contains a recursive call to itself, its running time can often be describedby a recurrence equation or recurrence, which describes the overall running time on aproblem of size n in terms of the running time on smaller inputs. We can then usemathematical tools to solve the recurrence and provide bounds on the performance of thealgorithm.A recurrence for the running time of a divide-and-conquer algorithm is based on the threesteps of the basic paradigm. As before, we let T (n) be the running time on a problem of sizen. If the problem size is small enough, say n ≤ c for some constant c, the straightforwardsolution takes constant time, which we write as Θ(1). Suppose that our division of theproblem yields a subproblems, each of which is 1/b the size of the original. (For merge sort,both a and b are 2, but we shall see many divide-and-conquer algorithms in which a ≠ b.) Ifwe take D(n) time to divide the problem into subproblems and C(n) time to combine thesolutions to the subproblems into the solution to the original problem, we get the recurrenceIn Chapter 4, we shall see how to solve common recurrences of this form.Analysis of merge sortAlthough the pseudocode for MERGE-SORT works correctly when the number of elements isnot even, our recurrence-based analysis is simplified if we assume that the original problemsize is a power of 2. Each divide step then yields two subsequences of size exactly n/2. InChapter 4, we shall see that this assumption does not affect the order of growth of the solutionto the recurrence.We reason as follows to set up the recurrence for T (n), the worst-case running time of mergesort on n numbers. Merge sort on just one element takes constant time. When we have n > 1elements, we break down the running time as follows. • Divide: The divide step just computes the middle of the subarray, which takes constant time. Thus, D(n) = Θ(1). • Conquer: We recursively solve two subproblems, each of size n/2, which contributes 2T (n/2) to the running time. • Combine: We have already noted that the MERGE procedure on an n-element subarray takes time Θ(n), so C(n) = Θ(n).When we add the functions D(n) and C(n) for the merge sort analysis, we are adding afunction that is Θ(n) and a function that is Θ(1). This sum is a linear function of n, that is,Θ(n). Adding it to the 2T (n/2) term from the "conquer" step gives the recurrence for theworst-case running time T (n) of merge sort:(2.1)In Chapter 4, we shall see the "master theorem," which we can use to show that T (n) is Θ(n lgn), where lg n stands for log2 n. Because the logarithm function grows more slowly than any
  • 34. linear function, for large enough inputs, merge sort, with its Θ(n lg n) running time,outperforms insertion sort, whose running time is Θ(n2), in the worst case.We do not need the master theorem to intuitively understand why the solution to therecurrence (2.1) is T (n) = Θ(n lg n). Let us rewrite recurrence (2.1) as(2.2)where the constant c represents the time required to solve problems of size 1 as well as thetime per array element of the divide and combine steps.[8]Figure 2.5 shows how we can solve the recurrence (2.2). For convenience, we assume that n isan exact power of 2. Part (a) of the figure shows T (n), which in part (b) has been expandedinto an equivalent tree representing the recurrence. The cn term is the root (the cost at the toplevel of recursion), and the two subtrees of the root are the two smaller recurrences T (n/2).Part (c) shows this process carried one step further by expanding T (n/2). The cost for each ofthe two subnodes at the second level of recursion is cn/2. We continue expanding each nodein the tree by breaking it into its constituent parts as determined by the recurrence, until theproblem sizes get down to 1, each with a cost of c. Part (d) shows the resulting tree.Figure 2.5: The construction of a recursion tree for the recurrence T(n) = 2T(n/2) + cn. Part(a) shows T(n), which is progressively expanded in (b)-(d) to form the recursion tree. The
  • 35. fully expanded tree in part (d) has lg n + 1 levels (i.e., it has height lg n, as indicated), andeach level contributes a total cost of cn. The total cost, therefore, is cn lg n + cn, which is Θ(nlg n).Next, we add the costs across each level of the tree. The top level has total cost cn, the nextlevel down has total cost c(n/2) + c(n/2) = cn, the level after that has total cost c(n/4) + c(n/4)+ c(n/4) + c(n/4) = cn, and so on. In general, the level i below the top has 2i nodes, eachcontributing a cost of c(n/2i), so that the ith level below the top has total cost 2i c(n/2i) = cn.At the bottom level, there are n nodes, each contributing a cost of c, for a total cost of cn.The total number of levels of the "recursion tree" in Figure 2.5 is lg n + 1. This fact is easilyseen by an informal inductive argument. The base case occurs when n = 1, in which case thereis only one level. Since lg 1 = 0, we have that lg n + 1 gives the correct number of levels.Now assume as an inductive hypothesis that the number of levels of a recursion tree for 2inodes is lg 2i + 1 = i + 1 (since for any value of i, we have that lg 2i = i). Because we areassuming that the original input size is a power of 2, the next input size to consider is 2i+1. Atree with 2i+1 nodes has one more level than a tree of 2i nodes, and so the total number oflevels is (i + 1) + 1 = lg 2i+1 + 1.To compute the total cost represented by the recurrence (2.2), we simply add up the costs ofall the levels. There are lg n + 1 levels, each costing cn, for a total cost of cn(lg n + 1) = cn lgn + cn. Ignoring the low-order term and the constant c gives the desired result of Θ(n lg n).Exercises 2.3-1Using Figure 2.4 as a model, illustrate the operation of merge sort on the array A = 3, 41,52, 26, 38, 57, 9, 49 .Exercises 2.3-2Rewrite the MERGE procedure so that it does not use sentinels, instead stopping once eitherarray L or R has had all its elements copied back to A and then copying the remainder of theother array back into A.Exercises 2.3-3Use mathematical induction to show that when n is an exact power of 2, the solution of therecurrence
  • 36. Exercises 2.3-4Insertion sort can be expressed as a recursive procedure as follows. In order to sort A[1 n],we recursively sort A[1 n -1] and then insert A[n] into the sorted array A[1 n - 1]. Write arecurrence for the running time of this recursive version of insertion sort.Exercises 2.3-5Referring back to the searching problem (see Exercise 2.1-3), observe that if the sequence A issorted, we can check the midpoint of the sequence against v and eliminate half of thesequence from further consideration. Binary search is an algorithm that repeats thisprocedure, halving the size of the remaining portion of the sequence each time. Writepseudocode, either iterative or recursive, for binary search. Argue that the worst-case runningtime of binary search is Θ(lg n).Exercises 2.3-6Observe that the while loop of lines 5 - 7 of the INSERTION-SORT procedure in Section 2.1uses a linear search to scan (backward) through the sorted subarray A[1 j - 1]. Can we use abinary search (see Exercise 2.3-5) instead to improve the overall worst-case running time ofinsertion sort to Θ(n lg n)?Exercises 2.3-7:Describe a Θ(n lg n)-time algorithm that, given a set S of n integers and another integer x,determines whether or not there exist two elements in S whose sum is exactly x.Problems 2-1: Insertion sort on small arrays in merge sortAlthough merge sort runs in Θ(n lg n) worst-case time and insertion sort runs in Θ(n2) worst-case time, the constant factors in insertion sort make it faster for small n. Thus, it makes senseto use insertion sort within merge sort when subproblems become sufficiently small. Considera modification to merge sort in which n/k sublists of length k are sorted using insertion sortand then merged using the standard merging mechanism, where k is a value to be determined.
  • 37. a. Show that the n/k sublists, each of length k, can be sorted by insertion sort in Θ(nk) worst-case time. b. Show that the sublists can be merged in Θ(n lg (n/k) worst-case time. c. Given that the modified algorithm runs in Θ(nk + n lg (n/k)) worst-case time, what is the largest asymptotic (Θnotation) value of k as a function of n for which the modified algorithm has the same asymptotic running time as standard merge sort? d. How should k be chosen in practice?Problems 2-2: Correctness of bubblesortBubblesort is a popular sorting algorithm. It works by repeatedly swapping adjacent elementsthat are out of order.BUBBLESORT(A)1 for i ← 1 to length[A]2 do for j ← length[A] downto i + 13 do if A[j] < A[j - 1]4 then exchange A[j] ↔ A[j - 1] a. Let A′ denote the output of BUBBLESORT(A). To prove that BUBBLESORT is correct, we need to prove that it terminates and that (2.3) b. where n = length[A]. What else must be proved to show that BUBBLESORT actually sorts?The next two parts will prove inequality (2.3). b. State precisely a loop invariant for the for loop in lines 2-4, and prove that this loop invariant holds. Your proof should use the structure of the loop invariant proof presented in this chapter. c. Using the termination condition of the loop invariant proved in part (b), state a loop invariant for the for loop in lines 1-4 that will allow you to prove inequality (2.3). Your proof should use the structure of the loop invariant proof presented in this chapter. d. What is the worst-case running time of bubblesort? How does it compare to the running time of insertion sort?Problems 2-3: Correctness of Horners ruleThe following code fragment implements Horners rule for evaluating a polynomial
  • 38. given the coefficients a0, a1, . . . , an and a value for x:1 y ← 02 i ← n3 while i ≥ 04 do y ← ai + x · y5 i ← i - 1 a. What is the asymptotic running time of this code fragment for Horners rule? b. Write pseudocode to implement the naive polynomial-evaluation algorithm that computes each term of the polynomial from scratch. What is the running time of this algorithm? How does it compare to Horners rule? c. Prove that the following is a loop invariant for the while loop in lines 3 -5. At the start of each iteration of the
  • 39. The expression ⌈x⌉ denotes the least integer greater than or equal to x, and ⌊x⌋ denotes the[7]greatest integer less than or equal to x. These notations are defined in Chapter 3. The easiestway to verify that setting q to ⌊( p + r)/2⌋ yields subarrays A[p q] and A[q + 1 r] of sizes⌈n/2⌉ and ⌊n/2⌋, respectively, is to examine the four cases that arise depending on whethereach of p and r is odd or even.[8] It is unlikely that the same constant exactly represents both the time to solve problems ofsize 1 and the time per array element of the divide and combine steps. We can get around thisproblem by letting c be the larger of these times and understanding that our recurrence givesan upper bound on the running time, or by letting c be the lesser of these times andunderstanding that our recurrence gives a lower bound on the running time. Both bounds willbe on the order of n lg n and, taken together, give a Θ(n lg n) running time.Chapter notesIn 1968, Knuth published the first of three volumes with the general title The Art of ComputerProgramming [182, 183, 185]. The first volume ushered in the modern study of computeralgorithms with a focus on the analysis of running time, and the full series remains anengaging and worthwhile reference for many of the topics presented here. According toKnuth, the word "algorithm" is derived from the name "al-Khowârizmî," a ninth-centuryPersian mathematician.Aho, Hopcroft, and Ullman [5] advocated the asymptotic analysis of algorithms as a means ofcomparing relative performance. They also popularized the use of recurrence relations todescribe the running times of recursive algorithms.Knuth [185] provides an encyclopedic treatment of many sorting algorithms. His comparisonof sorting algorithms (page 381) includes exact step-counting analyses, like the one weperformed here for insertion sort. Knuths discussion of insertion sort encompasses severalvariations of the algorithm. The most important of these is Shells sort, introduced by D. L.Shell, which uses insertion sort on periodic subsequences of the input to produce a fastersorting algorithm.Merge sort is also described by Knuth. He mentions that a mechanical collator capable ofmerging two decks of punched cards in a single pass was invented in 1938. J. von Neumann,one of the pioneers of computer science, apparently wrote a program for merge sort on theEDVAC computer in 1945.The early history of proving programs correct is described by Gries [133], who credits P.Naur with the first article in this field. Gries attributes loop invariants to R. W. Floyd. Thetextbook by Mitchell [222] describes more recent progress in proving programs correct.Chapter 3: Growth of FunctionsOverview
  • 40. The order of growth of the running time of an algorithm, defined in Chapter 2, gives a simplecharacterization of the algorithms efficiency and also allows us to compare the relativeperformance of alternative algorithms. Once the input size n becomes large enough, mergesort, with its Θ(n lg n) worst-case running time, beats insertion sort, whose worst-case runningtime is Θ(n2). Although we can sometimes determine the exact running time of an algorithm,as we did for insertion sort in Chapter 2, the extra precision is not usually worth the effort ofcomputing it. For large enough inputs, the multiplicative constants and lower-order terms ofan exact running time are dominated by the effects of the input size itself.When we look at input sizes large enough to make only the order of growth of the runningtime relevant, we are studying the asymptotic efficiency of algorithms. That is, we areconcerned with how the running time of an algorithm increases with the size of the input inthe limit, as the size of the input increases without bound. Usually, an algorithm that isasymptotically more efficient will be the best choice for all but very small inputs.This chapter gives several standard methods for simplifying the asymptotic analysis ofalgorithms. The next section begins by defining several types of "asymptotic notation," ofwhich we have already seen an example in Θ-notation. Several notational conventions usedthroughout this book are then presented, and finally we review the behavior of functions thatcommonly arise in the analysis of algorithms.3.1 Asymptotic notationThe notations we use to describe the asymptotic running time of an algorithm are defined interms of functions whose domains are the set of natural numbers N = {0, 1, 2, ...}. Suchnotations are convenient for describing the worst-case running-time function T (n), which isusually defined only on integer input sizes. It is sometimes convenient, however, to abuseasymptotic notation in a variety of ways. For example, the notation is easily extended to thedomain of real numbers or, alternatively, restricted to a subset of the natural numbers. It isimportant, however, to understand the precise meaning of the notation so that when it isabused, it is not misused. This section defines the basic asymptotic notations and alsointroduces some common abuses.Θ-notationIn Chapter 2, we found that the worst-case running time of insertion sort is T (n) = Θ(n2). Letus define what this notation means. For a given function g(n), we denote by Θ(g(n)) the set offunctionsΘ(g(n)) = {f(n) : there exist positive constants c1, c2, and n0 such that 0 ≤ c1g(n) ≤ f(n) ≤ c2g(n)for all n ≥ n0}.[1]A function f(n) belongs to the set Θ(g(n)) if there exist positive constants c1 and c2 such that itcan be "sandwiched" between c1g(n) and c2g(n), for sufficiently large n. Because Θ(g(n)) is aset, we could write "f(n) Θ(g(n))" to indicate that f(n) is a member of Θ(g(n)). Instead, wewill usually write "f(n) = Θ(g(n))" to express the same notion. This abuse of equality to denoteset membership may at first appear confusing, but we shall see later in this section that it hasadvantages.
  • 41. Figure 3.1(a) gives an intuitive picture of functions f(n) and g(n), where we have that f(n) =Θ(g(n)). For all values of n to the right of n0, the value of f(n) lies at or above c1g(n) and at orbelow c2g(n). In other words, for all n ≥ n0, the function f(n) is equal to g(n) to within aconstant factor. We say that g(n) is an asymptotically tight bound for f(n).Figure 3.1: Graphic examples of the Θ, O, and Ω notations. In each part, the value of n0shown is the minimum possible value; any greater value would also work. (a) Θ-notationbounds a function to within constant factors. We write f(n) = Θ(g(n)) if there exist positiveconstants n0, c1, and c2 such that to the right of n0, the value of f(n) always lies between c1g(n)and c2g(n) inclusive. (b) O-notation gives an upper bound for a function to within a constantfactor. We write f(n) = O(g(n)) if there are positive constants n0 and c such that to the right ofn0, the value of f(n) always lies on or below cg(n). (c) Ω-notation gives a lower bound for afunction to within a constant factor. We write f(n) = Ω(g(n)) if there are positive constants n0and c such that to the right of n0, the value of f(n) always lies on or above cg(n).The definition of Θ(g(n)) requires that every member f(n) Θ(g(n)) be asymptoticallynonnegative, that is, that f(n) be nonnegative whenever n is sufficiently large. (Anasymptotically positive function is one that is positive for all sufficiently large n.)Consequently, the function g(n) itself must be asymptotically nonnegative, or else the setΘ(g(n)) is empty. We shall therefore assume that every function used within Θ-notation isasymptotically nonnegative. This assumption holds for the other asymptotic notations definedin this chapter as well.In Chapter 2, we introduced an informal notion of Θ-notation that amounted to throwing awaylower-order terms and ignoring the leading coefficient of the highest-order term. Let usbriefly justify this intuition by using the formal definition to show that 1/2n2 - 3n = Θ(n2). Todo so, we must determine positive constants c1, c2, and n0 such thatc1n2 ≤ 1/2n2 - 3n ≤ c2n2for all n ≥ n0. Dividing by n2 yieldsc1 ≤ 1/2 - 3/n ≤ c2.The right-hand inequality can be made to hold for any value of n ≥ 1 by choosing c2 ≥ 1/2.Likewise, the left-hand inequality can be made to hold for any value of n ≥ 7 by choosing c1 ≤1/14. Thus, by choosing c1 = 1/14, c2 = 1/2, and n0 = 7, we can verify that 1/2n2 - 3n = Θ(n2).Certainly, other choices for the constants exist, but the important thing is that some choiceexists. Note that these constants depend on the function 1/2n2 - 3n; a different functionbelonging to Θ(n2) would usually require different constants.We can also use the formal definition to verify that 6n3 ≠ Θ(n2). Suppose for the purpose ofcontradiction that c2 and n0 exist such that 6n3 ≤ c2n2 for all n ≥ n0. But then n ≤ c2/6, whichcannot possibly hold for arbitrarily large n, since c2 is constant.
  • 42. Intuitively, the lower-order terms of an asymptotically positive function can be ignored indetermining asymptotically tight bounds because they are insignificant for large n. A tinyfraction of the highest-order term is enough to dominate the lower-order terms. Thus, settingc1 to a value that is slightly smaller than the coefficient of the highest-order term and settingc2 to a value that is slightly larger permits the inequalities in the definition of Θ-notation to besatisfied. The coefficient of the highest-order term can likewise be ignored, since it onlychanges c1 and c2 by a constant factor equal to the coefficient.As an example, consider any quadratic function f(n) = an2 + bn + c, where a, b, and c areconstants and a > 0. Throwing away the lower-order terms and ignoring the constant yieldsf(n) = Θ(n2). Formally, to show the same thing, we take the constants c1 = a/4, c2 = 7a/4, and . The reader may verify that 0 ≤ c1n2 ≤ an2 + bn + c ≤ c2n2 for all n ≥ n0.In general, for any polynomial , where the ai are constants and ad > 0, we have dp(n) = Θ(n ) (see Problem 3-1).Since any constant is a degree-0 polynomial, we can express any constant function as Θ(n0),or Θ(1). This latter notation is a minor abuse, however, because it is not clear what variable istending to infinity.[2] We shall often use the notation Θ(1) to mean either a constant or aconstant function with respect to some variable.O-notationThe Θ-notation asymptotically bounds a function from above and below. When we have onlyan asymptotic upper bound, we use O-notation. For a given function g(n), we denote byO(g(n)) (pronounced "big-oh of g of n" or sometimes just "oh of g of n") the set of functionsO(g(n)) = {f(n): there exist positive constants c and n0 such that 0 ≤ f(n) ≤ cg(n) for all n ≥n0}.We use O-notation to give an upper bound on a function, to within a constant factor. Figure3.1(b) shows the intuition behind O-notation. For all values n to the right of n0, the value ofthe function f(n) is on or below g(n).We write f(n) = O(g(n)) to indicate that a function f(n) is a member of the set O(g(n)). Notethat f(n) = Θ(g(n)) implies f(n) = O(g(n)), since Θ-notation is a stronger notion than O-notation. Written set-theoretically, we have Θ(g(n)) O(g(n)). Thus, our proof that anyquadratic function an2 + bn + c, where a > 0, is in Θ(n2) also shows that any quadraticfunction is in O(n2). What may be more surprising is that any linear function an + b is inO(n2), which is easily verified by taking c = a + |b| and n0 = 1.Some readers who have seen O-notation before may find it strange that we should write, forexample, n = O(n2). In the literature, O-notation is sometimes used informally to describeasymptotically tight bounds, that is, what we have defined using Θ-notation. In this book,however, when we write f(n) = O(g(n)), we are merely claiming that some constant multipleof g(n) is an asymptotic upper bound on f(n), with no claim about how tight an upper bound itis. Distinguishing asymptotic upper bounds from asymptotically tight bounds has nowbecome standard in the algorithms literature.Using O-notation, we can often describe the running time of an algorithm merely byinspecting the algorithms overall structure. For example, the doubly nested loop structure of
  • 43. the insertion sort algorithm from Chapter 2 immediately yields an O(n2) upper bound on theworst-case running time: the cost of each iteration of the inner loop is bounded from above byO(1) (constant), the indices i and j are both at most n, and the inner loop is executed at mostonce for each of the n2 pairs of values for i and j.Since O-notation describes an upper bound, when we use it to bound the worst-case runningtime of an algorithm, we have a bound on the running time of the algorithm on every input.Thus, the O(n2) bound on worst-case running time of insertion sort also applies to its runningtime on every input. The Θ(n2) bound on the worst-case running time of insertion sort,however, does not imply a Θ(n2) bound on the running time of insertion sort on every input.For example, we saw in Chapter 2 that when the input is already sorted, insertion sort runs inΘ(n) time.Technically, it is an abuse to say that the running time of insertion sort is O(n2), since for agiven n, the actual running time varies, depending on the particular input of size n. When wesay "the running time is O(n2)," we mean that there is a function f(n) that is O(n2) such that forany value of n, no matter what particular input of size n is chosen, the running time on thatinput is bounded from above by the value f(n). Equivalently, we mean that the worst-caserunning time is O(n2).Ω-notationJust as O-notation provides an asymptotic upper bound on a function, Ω-notation provides anasymptotic lower bound. For a given function g(n), we denote by Ω(g(n)) (pronounced "big-omega of g of n" or sometimes just "omega of g of n") the set of functionsΩ(g(n)) = {f(n): there exist positive constants c and n0 such that 0 ≤ cg(n) ≤ f(n) for all n ≥n0}.The intuition behind Ω-notation is shown in Figure 3.1(c). For all values n to the right of n0,the value of f(n) is on or above cg(n).From the definitions of the asymptotic notations we have seen thus far, it is easy to prove thefollowing important theorem (see Exercise 3.1-5).Theorem 3.1For any two functions f(n) and g(n), we have f(n) = Θ(g(n)) if and only if f(n) = O(g(n)) andf(n) = Ω(g(n)).As an example of the application of this theorem, our proof that an2 + bn + c = Θ(n2) for anyconstants a, b, and c, where a > 0, immediately implies that an2 + bn + c = Ω(n2) and an2 + bn+ c = O(n2). In practice, rather than using Theorem 3.1 to obtain asymptotic upper and lowerbounds from asymptotically tight bounds, as we did for this example, we usually use it toprove asymptotically tight bounds from asymptotic upper and lower bounds.
  • 44. Since Ω-notation describes a lower bound, when we use it to bound the best-case runningtime of an algorithm, by implication we also bound the running time of the algorithm onarbitrary inputs as well. For example, the best-case running time of insertion sort is Ω(n),which implies that the running time of insertion sort is Ω(n).The running time of insertion sort therefore falls between Ω(n) and O(n2), since it fallsanywhere between a linear function of n and a quadratic function of n. Moreover, thesebounds are asymptotically as tight as possible: for instance, the running time of insertion sortis not Ω(n2), since there exists an input for which insertion sort runs in Θ(n) time (e.g., whenthe input is already sorted). It is not contradictory, however, to say that the worst-case runningtime of insertion sort is Ω(n2), since there exists an input that causes the algorithm to takeΩ(n2) time. When we say that the running time (no modifier) of an algorithm is Ω(g(n)), wemean that no matter what particular input of size n is chosen for each value of n, the runningtime on that input is at least a constant times g(n), for sufficiently large n.Asymptotic notation in equations and inequalitiesWe have already seen how asymptotic notation can be used within mathematical formulas.For example, in introducing O-notation, we wrote "n = O(n2)." We might also write 2n2 + 3n+ 1 = 2n2 + Θ(n). How do we interpret such formulas?When the asymptotic notation stands alone on the right-hand side of an equation (orinequality), as in n = O(n2), we have already defined the equal sign to mean set membership:n O(n2). In general, however, when asymptotic notation appears in a formula, we interpretit as standing for some anonymous function that we do not care to name. For example, theformula 2n2 + 3n + 1 = 2n2 + Θ(n) means that 2n2 + 3n + 1 = 2n2 + f(n), where f(n) is somefunction in the set Θ(n). In this case, f(n) = 3n + 1, which indeed is in Θ(n).Using asymptotic notation in this manner can help eliminate inessential detail and clutter in anequation. For example, in Chapter 2 we expressed the worst-case running time of merge sortas the recurrenceT(n) = 2T (n/2) + Θ(n).If we are interested only in the asymptotic behavior of T(n), there is no point in specifying allthe lower-order terms exactly; they are all understood to be included in the anonymousfunction denoted by the term Θ(n).The number of anonymous functions in an expression is understood to be equal to the numberof times the asymptotic notation appears. For example, in the expressionthere is only a single anonymous function (a function of i). This expression is thus not thesame as O(1) + O(2) + . . . + O(n), which doesnt really have a clean interpretation.In some cases, asymptotic notation appears on the left-hand side of an equation, as in2n2 + Θ(n) = Θ(n2).
  • 45. We interpret such equations using the following rule: No matter how the anonymous functionsare chosen on the left of the equal sign, there is a way to choose the anonymous functions onthe right of the equal sign to make the equation valid. Thus, the meaning of our example isthat for any function f(n) Θ(n), there is some function g(n) Θ(n2) such that 2n2 + f(n) =g(n) for all n. In other words, the right-hand side of an equation provides a coarser level ofdetail than the left-hand side.A number of such relationships can be chained together, as in2n2 + 3n + 1 = 2n2 + Θ(n) = Θ(n2).We can interpret each equation separately by the rule above. The first equation says that thereis some function f(n) Θ(n) such that 2n2 + 3n + 1 = 2n2 + f(n) for all n. The second equationsays that for any function g(n) Θ(n) (such as the f(n) just mentioned), there is some functionh(n) Θ(n2) such that 2n2 + g(n) = h(n) for all n. Note that this interpretation implies that 2n2+ 3n + 1 = Θ(n2), which is what the chaining of equations intuitively gives us.o-notationThe asymptotic upper bound provided by O-notation may or may not be asymptotically tight.The bound 2n2 = O(n2) is asymptotically tight, but the bound 2n = O(n2) is not. We use o-notation to denote an upper bound that is not asymptotically tight. We formally define o(g(n))("little-oh of g of n") as the seto(g(n)) = {f(n) : for any positive constant c > 0, there exists a constant n0 > 0 such that 0 ≤ f(n)< cg(n) for all n ≥ n0}.For example, 2n = o(n2), but 2n2 ≠ o(n2).The definitions of O-notation and o-notation are similar. The main difference is that in f(n) =O(g(n)), the bound 0 ≤ f(n) ≤ cg(n) holds for some constant c > 0, but in f(n) = o(g(n)), thebound 0 ≤ f(n) < cg(n) holds for all constants c > 0. Intuitively, in the o-notation, the functionf(n) becomes insignificant relative to g(n) as n approaches infinity; that is,(3.1)Some authors use this limit as a definition of the o-notation; the definition in this book alsorestricts the anonymous functions to be asymptotically nonnegative.ω-notationBy analogy, ω-notation is to Ω-notation as o-notation is to O-notation. We use ω-notation todenote a lower bound that is not asymptotically tight. One way to define it is byf(n) ω(g(n)) if and only if g(n) o(f(n)).Formally, however, we define ω(g(n)) ("little-omega of g of n") as the set
  • 46. ω(g(n)) = {f(n): for any positive constant c > 0, there exists a constant n0 > 0 such that 0 ≤cg(n) < f(n) for all n ≥ n0}.For example, n2/2 = ω(n), but n2/2 ≠ ω(n2). The relation f(n) = ω(g(n)) implies thatif the limit exists. That is, f(n) becomes arbitrarily large relative to g(n) as n approachesinfinity.Comparison of functionsMany of the relational properties of real numbers apply to asymptotic comparisons as well.For the following, assume that f(n) and g(n) are asymptotically positive.Transitivity: • f(n) = Θ(g(n)) and g(n) = Θ(h(n)) imply f(n) = Θ(h(n)), f(n) = O(g(n)) and g(n) = O(h(n)) imply f(n) = O(h(n)), f(n) = Ω(g(n)) and g(n) = Ω(h(n)) imply f(n) = Ω(h(n)), f(n) = o(g(n)) and g(n) = o(h(n)) imply f(n) = o(h(n)), f(n) = ω(g(n)) and g(n) = ω(h(n)) imply f(n) = ω(h(n)).Reflexivity: • f(n) = Θ(f(n)), f(n) = O(f(n)), f(n) = Ω(f(n)).Symmetry:f(n) = Θ(g(n)) if and only if g(n) = Θ(f(n)).Transpose symmetry: • f(n) = O(g(n)) if and only if g(n) = Ω(f(n)), f(n) = o(g(n)) if and only if g(n) = ω(f(n)).Because these properties hold for asymptotic notations, one can draw an analogy between theasymptotic comparison of two functions f and g and the comparison of two real numbers aand b:
  • 47. f(n) = O(g(n)) ≈ a ≤ b,f(n) = Ω(g(n)) ≈ a ≥ b,f(n) = Θ(g(n)) ≈ a = b,f(n) = o(g(n)) ≈ a < b,f(n) = ω(g(n)) ≈ a > b.We say that f(n) is asymptotically smaller than g(n) if f(n) = o(g(n)), and f(n) isasymptotically larger than g(n) if f(n) = ω(g(n)).One property of real numbers, however, does not carry over to asymptotic notation: • Trichotomy: For any two real numbers a and b, exactly one of the following must hold: a < b, a = b, or a > b.Although any two real numbers can be compared, not all functions are asymptoticallycomparable. That is, for two functions f(n) and g(n), it may be the case that neither f(n) =O(g(n)) nor f(n) = Ω(g(n)) holds. For example, the functions n and n1+sin n cannot be comparedusing asymptotic notation, since the value of the exponent in n1+sin n oscillates between 0 and2, taking on all values in between.Exercises 3.1-1Let f(n) and g(n) be asymptotically nonnegative functions. Using the basic definition of Θ-notation, prove that max(f(n), g(n)) = Θ(f(n) + g(n)).Exercises 3.1-2Show that for any real constants a and b, where b > 0,(3.2)Exercises 3.1-3Explain why the statement, "The running time of algorithm A is at least O(n2)," ismeaningless.Exercises 3.1-4Is 2n+1 = O(2n)? Is 22n = O(2n)?
  • 48. Exercises 3.1-5Prove Theorem 3.1.Exercises 3.1-6Prove that the running time of an algorithm is Θ(g(n)) if and only if its worst-case runningtime is O(g(n)) and its best-case running time is Ω(g(n)).Exercises 3.1-7Prove that o(g(n)) ∩ ω(g(n)) is the empty set.Exercises 3.1-8We can extend our notation to the case of two parameters n and m that can go to infinityindependently at different rates. For a given function g(n, m), we denote by O(g(n, m)) the setof functionsO(g(n, m)) = {f(n, m): there exist positive constants c, n0, and m0 such that 0 ≤ f(n, m) ≤ cg(n,m) for all n ≥ n0 and m ≥ m0}.Give corresponding definitions for Ω(g(n, m)) and Θ(g(n, m)).[1] Within set notation, a colon should be read as "such that."[2] The real problem is that our ordinary notation for functions does not distinguish functionsfrom values. In λ-calculus, the parameters to a function are clearly specified: the function n2could be written as λn.n2, or even λr.r2. Adopting a more rigorous notation, however, wouldcomplicate algebraic manipulations, and so we choose to tolerate the abuse.3.2 Standard notations and common functionsThis section reviews some standard mathematical functions and notations and explores therelationships among them. It also illustrates the use of the asymptotic notations.
  • 49. MonotonicityA function f(n) is monotonically increasing if m ≤ n implies f(m) ≤ f(n). Similarly, it ismonotonically decreasing if m ≤ n implies f(m) ≥ f(n). A function f(n) is strictly increasing ifm < n implies f(m) < f(n) and strictly decreasing if m < n implies f(m) > f(n).Floors and ceilingsFor any real number x, we denote the greatest integer less than or equal to x by ⌊x⌋ (read "thefloor of x") and the least integer greater than or equal to x by ⌈x⌉ (read "the ceiling of x"). Forall real x,(3.3)For any integer n,⌈n/2⌉ + ⌊n/2⌋ = n,and for any real number n ≥ 0 and integers a, b > 0,(3.4)(3.5)(3.6)(3.7)The floor function f(x) = ⌊x⌋ is monotonically increasing, as is the ceiling function f(x) = ⌈x⌉.Modular arithmeticFor any integer a and any positive integer n, the value a mod n is the remainder (or residue)of the quotient a/n:(3.8)Given a well-defined notion of the remainder of one integer when divided by another, it isconvenient to provide special notation to indicate equality of remainders. If (a mod n) = (bmod n), we write a ≡ b (mod n) and say that a is equivalent to b, modulo n. In other words, a≡ b (mod n) if a and b have the same remainder when divided by n. Equivalently, a ≡ b (modn) if and only if n is a divisor of b - a. We write a ≢ b (mod n) if a is not equivalent to b,modulo n.PolynomialsGiven a nonnegative integer d, a polynomial in n of degree d is a function p(n) of the form
  • 50. where the constants a0, a1, ..., ad are the coefficients of the polynomial and ad ≠ 0. Apolynomial is asymptotically positive if and only if ad > 0. For an asymptotically positivepolynomial p(n) of degree d, we have p(n) = Θ(nd). For any real constant a ≥ 0, the functionna is monotonically increasing, and for any real constant a ≥ 0, the function na ismonotonically decreasing. We say that a function f(n) is polynomially bounded if f(n) = O(nk)for some constant k.ExponentialsFor all real a > 0, m, and n, we have the following identities: a0 = 1, a1 = a, a-1 = 1/a,(am)n = amn,(am)n = (an)m,am an = am+n.For all n and a ≥ 1, the function an is monotonically increasing in n. When convenient, weshall assume 00 = 1.The rates of growth of polynomials and exponentials can be related by the following fact. Forall real constants a and b such that a > 1,(3.9)from which we can conclude thatnb = o(an).Thus, any exponential function with a base strictly greater than 1 grows faster than anypolynomial function.Using e to denote 2.71828..., the base of the natural logarithm function, we have for all real x,(3.10)where "!" denotes the factorial function defined later in this section. For all real x, we have theinequality(3.11)where equality holds only when x = 0. When |x| ≤ 1, we have the approximation(3.12)
  • 51. When x → 0, the approximation of ex by 1 + x is quite good:ex = 1 + x + Θ(x2).(In this equation, the asymptotic notation is used to describe the limiting behavior as x → 0rather than as x → ∞.) We have for all x,(3.13)LogarithmsWe shall use the following notations: lg n = log2 n (binary logarithm) , ln n = loge n (natural logarithm) , lgk n = (lg n)k (exponentiation) ,lg lg n = lg(lg n) (composition) .An important notational convention we shall adopt is that logarithm functions will apply onlyto the next term in the formula, so that lg n + k will mean (lg n) + k and not lg(n + k). If wehold b > 1 constant, then for n > 0, the function logb n is strictly increasing.For all real a > 0, b > 0, c > 0, and n,(3.14)(3.15)where, in each equation above, logarithm bases are not 1.By equation (3.14), changing the base of a logarithm from one constant to another onlychanges the value of the logarithm by a constant factor, and so we shall often use the notation"lg n" when we dont care about constant factors, such as in O-notation. Computer scientistsfind 2 to be the most natural base for logarithms because so many algorithms and datastructures involve splitting a problem into two parts.There is a simple series expansion for ln(1 + x) when |x| < 1:
  • 52. We also have the following inequalities for x > -1:(3.16)where equality holds only for x = 0.We say that a function f(n) is polylogarithmically bounded if f(n) = O(lgk n) for someconstant k. We can relate the growth of polynomials and polylogarithms by substituting lg nfor n and 2a for a in equation (3.9), yieldingFrom this limit, we can conclude thatlgb n = o(na)for any constant a > 0. Thus, any positive polynomial function grows faster than anypolylogarithmic function.FactorialsThe notation n! (read "n factorial") is defined for integers n ≥ 0 asThus, n! = 1 · 2 · 3 n.A weak upper bound on the factorial function is n! ≤ nn, since each of the n terms in thefactorial product is at most n. Stirlings approximation,(3.17)where e is the base of the natural logarithm, gives us a tighter upper bound, and a lower boundas well. One can prove (see Exercise 3.2-3)(3.18)where Stirlings approximation is helpful in proving equation (3.18). The following equationalso holds for all n ≥ 1:(3.19)
  • 53. where(3.20)Functional iterationWe use the notation f(i)(n) to denote the function f(n) iteratively applied i times to an initialvalue of n. Formally, let f(n) be a function over the reals. For nonnegative integers i, werecursively defineFor example, if f(n) = 2n, then f(i)(n) = 2in.The iterated logarithm functionWe use the notation lg* n (read "log star of n") to denote the iterated logarithm, which isdefined as follows. Let lg(i) n be as defined above, with f(n) = lg n. Because the logarithm of anonpositive number is undefined, lg(i) n is defined only if lg(i-1) n > 0. Be sure to distinguishlg(i) n (the logarithm function applied i times in succession, starting with argument n) from lgin (the logarithm of n raised to the ith power). The iterated logarithm function is defined aslg* n = min {i = 0: lg(i) n ≤ 1}.The iterated logarithm is a very slowly growing function: lg* 2 = 1, lg* 4 = 2, lg* 16 = 3,lg* 65536 = 4,lg*(265536) = 5.Since the number of atoms in the observable universe is estimated to be about 1080, which ismuch less than 265536, we rarely encounter an input size n such that lg* n > 5.Fibonacci numbersThe Fibonacci numbers are defined by the following recurrence:(3.21)Thus, each Fibonacci number is the sum of the two previous ones, yielding the sequence0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... .
  • 54. Fibonacci numbers are related to the golden ratio φ and to its conjugate , which are given bythe following formulas:(3.22)Specifically, we have(3.23)which can be proved by induction (Exercise 3.2-6). Since , we have ,so that the ith Fibonacci number Fi is equal to rounded to the nearest integer. Thus,Fibonacci numbers grow exponentially.Exercises 3.2-1Show that if f(n) and g(n) are monotonically increasing functions, then so are the functionsf(n) + g(n) and f (g(n)), and if f(n) and g(n) are in addition nonnegative, then f(n) · g(n) ismonotonically increasing.Exercises 3.2-2Prove equation (3.15).Exercises 3.2-3Prove equation (3.18). Also prove that n! = ω(2n) and n! = o(nn).Exercises 3.2-4:Is the function ⌈lg n⌉! polynomially bounded? Is the function ⌈lg lg n⌉! polynomiallybounded?
  • 55. Exercises 3.2-5:Which is asymptotically larger: lg(lg* n) or lg*(lg n)?Exercises 3.2-6Prove by induction that the ith Fibonacci number satisfies the equalitywhere φ is the golden ratio and is its conjugate.Exercises 3.2-7Prove that for i ≥ 0, the (i + 2)nd Fibonacci number satisfies Fi+2 ≥ φi.Problems 3-1: Asymptotic behavior of polynomialsLetwhere ad > 0, be a degree-d polynomial in n, and let k be a constant. Use the definitions of theasymptotic notations to prove the following properties. a. If k ≥ d, then p(n) = O(nk). b. If k ≤ d, then p(n) = Ω(nk). c. If k = d, then p(n) = Θ(nk). d. If k > d, then p(n) = o(nk). e. If k < d, then p(n) = ω(nk).Problems 3-2: Relative asymptotic growths
  • 56. Indicate, for each pair of expressions (A, B) in the table below, whether A is O, o, Ω, ω, or Θof B. Assume that k ≥ 1, > 0, and c > 1 are constants. Your answer should be in the form ofthe table with "yes" or "no" written in each box. A B OoΩωΘa. lgk n n kb. n cnc. nsin nd. 2n 2n/2e. nlg c clg nf. lg(n!) lg(nn)Problems 3-3: Ordering by asymptotic growth rates a. Rank the following functions by order of growth; that is, find an arrangement g1, g2, ..., g30 of the functions satisfying g1 = Ω(g2), g2 = Ω(g3), ..., g29 = Ω(g30). Partition your list into equivalence classes such that f(n) and g(n) are in the same class if and only if f(n) = Θ(g(n)). b. Give an example of a single nonnegative function f(n) such that for all functions gi(n) in part (a), f(n) is neither O(gi(n)) nor Ω(gi(n)).Problems 3-4: Asymptotic notation propertiesLet f(n) and g(n) be asymptotically positive functions. Prove or disprove each of the followingconjectures. a. f(n) = O(g(n)) implies g(n) = O(f(n)). b. f(n) + g(n) = Θ(min(f(n), g(n))). c. f(n) = O(g(n)) implies lg(f(n)) = O(lg(g(n))), where lg(g(n)) ≥ 1 and f(n) ≥ 1 for all sufficiently large n. d. f(n) = O(g(n)) implies 2f(n) = O (2g(n)). e. f(n) = O((f(n))2). f. f(n) = O(g(n)) implies g(n) = Ω(f(n)).
  • 57. g. f(n) = Θ(f(n/2)). h. f(n) + o( f(n)) = Θ(f(n)).Problems 3-5: Variations on O and ΩSome authors define Ω in a slightly different way than we do; lets use (read "omegainfinity") for this alternative definition. We say that if there exists a positiveconstant c such that f(n) ≥ cg(n) ≥ 0 for infinitely many integers n. a. Show that for any two functions f(n) and g(n) that are asymptotically nonnegative, either f(n) = O(g(n)) or or both, whereas this is not true if we use Ω in place of . b. Describe the potential advantages and disadvantages of using instead of Ω to characterize the running times of programs.Some authors also define O in a slightly different manner; lets use O for the alternativedefinition. We say that f(n) = O(g(n)) if and only if |f(n)| = O(g(n)). c. What happens to each direction of the "if and only if" in Theorem 3.1 if we substitute O for O but still use Ω?Some authors define Õ (read "soft-oh") to mean O with logarithmic factors ignored:Õ (g(n)) = {f(n): there exist positive constants c, k, and n0 such that 0 ≤ f(n) ≤ cg(n) lgk(n) forall n ≥ n0}. d. Define and in a similar manner. Prove the corresponding analog to Theorem 3.1.Problems 3-6: Iterated functionsThe iteration operator* used in the lg* function can be applied to any monotonicallyincreasing function f(n) over the reals. For a given constant c R, we define the iteratedfunction bywhich need not be well-defined in all cases. In other words, the quantity is the number ofiterated applications of the function f required to reduce its argument down to c or less.For each of the following functions f(n) and constants c, give as tight a bound as possible on . f(n) c
  • 58. f(n) ca. n - 1 0b. lg n 1c. n/2 1d. n/2 2e. 2f. 1g. n1/3 2h. n/lg n 2Chapter notesKnuth [182] traces the origin of the O-notation to a number-theory text by P. Bachmann in1892. The o-notation was invented by E. Landau in 1909 for his discussion of the distributionof prime numbers. The Ω and Θ notations were advocated by Knuth [186] to correct thepopular, but technically sloppy, practice in the literature of using O-notation for both upperand lower bounds. Many people continue to use the O-notation where the Θ-notation is moretechnically precise. Further discussion of the history and development of asymptotic notationscan be found in Knuth [182, 186] and Brassard and Bratley [46].Not all authors define the asymptotic notations in the same way, although the variousdefinitions agree in most common situations. Some of the alternative definitions encompassfunctions that are not asymptotically nonnegative, as long as their absolute values areappropriately bounded.Equation (3.19) is due to Robbins [260]. Other properties of elementary mathematicalfunctions can be found in any good mathematical reference, such as Abramowitz and Stegun[1] or Zwillinger [320], or in a calculus book, such as Apostol [18] or Thomas and Finney[296]. Knuth [182] and Graham, Knuth, and Patashnik [132] contain a wealth of material ondiscrete mathematics as used in computer science.TechnicalitiesIn practice, we neglect certain technical details when we state and solve recurrences. A goodexample of a detail that is often glossed over is the assumption of integer arguments tofunctions. Normally, the running time T (n) of an algorithm is only defined when n is aninteger, since for most algorithms, the size of the input is always an integer. For example, therecurrence describing the worst-case running time of MERGE-SORT is really(4.2)Boundary conditions represent another class of details that we typically ignore. Since therunning time of an algorithm on a constant-sized input is a constant, the recurrences that arisefrom the running times of algorithms generally have T(n) = Θ(1) for sufficiently small n.Consequently, for convenience, we shall generally omit statements of the boundary conditions
  • 59. of recurrences and assume that T (n) is constant for small n. For example, we normally staterecurrence (4.1) as(4.3)without explicitly giving values for small n. The reason is that although changing the value ofT (1) changes the solution to the recurrence, the solution typically doesnt change by morethan a constant factor, so the order of growth is unchanged.When we state and solve recurrences, we often omit floors, ceilings, and boundary conditions.We forge ahead without these details and later determine whether or not they matter. Theyusually dont, but it is important to know when they do. Experience helps, and so do sometheorems stating that these details dont affect the asymptotic bounds of many recurrencesencountered in the analysis of algorithms (see Theorem 4.1). In this chapter, however, weshall address some of these details to show the fine points of recurrence solution methods.4.1 The substitution methodThe substitution method for solving recurrences entails two steps: 1. Guess the form of the solution. 2. Use mathematical induction to find the constants and show that the solution works.The name comes from the substitution of the guessed answer for the function when theinductive hypothesis is applied to smaller values. This method is powerful, but it obviouslycan be applied only in cases when it is easy to guess the form of the answer.The substitution method can be used to establish either upper or lower bounds on arecurrence. As an example, let us determine an upper bound on the recurrence(4.4)which is similar to recurrences (4.2) and (4.3). We guess that the solution is T (n) = O(n lg n).Our method is to prove that T (n) ≤ cn lg n for an appropriate choice of the constant c > 0. Westart by assuming that this bound holds for ⌊n/2⌋, that is, that T (⌊n/2⌋) ≤ c ⌊n/2⌋ lg(⌊n/2⌋).Substituting into the recurrence yieldsT(n) ≤ 2(c ⌊n/2⌋lg(⌊n/2⌋)) + n ≤ cn lg(n/2) + n = cn lg n - cn lg 2 + n = cn lg n - cn + n ≤ cn lg n,where the last step holds as long as c ≥ 1.Mathematical induction now requires us to show that our solution holds for the boundaryconditions. Typically, we do so by showing that the boundary conditions are suitable as basecases for the inductive proof. For the recurrence (4.4), we must show that we can choose the
  • 60. constant c large enough so that the bound T(n) = cn lg n works for the boundary conditions aswell. This requirement can sometimes lead to problems. Let us assume, for the sake ofargument, that T (1) = 1 is the sole boundary condition of the recurrence. Then for n = 1, thebound T (n) = cn lg n yields T (1) = c1 lg 1 = 0, which is at odds with T (1) = 1. Consequently,the base case of our inductive proof fails to hold.This difficulty in proving an inductive hypothesis for a specific boundary condition can beeasily overcome. For example, in the recurrence (4.4), we take advantage of asymptoticnotation only requiring us to prove T (n) = cn lg n for n ≥ n0, where n0 is a constant of ourchoosing. The idea is to remove the difficult boundary condition T (1) = 1 from considerationin the inductive proof. Observe that for n > 3, the recurrence does not depend directly on T(1). Thus, we can replace T (1) by T (2) and T (3) as the base cases in the inductive proof,letting n0 = 2. Note that we make a distinction between the base case of the recurrence (n = 1)and the base cases of the inductive proof (n = 2 and n = 3). We derive from the recurrence thatT (2) = 4 and T (3) = 5. The inductive proof that T (n) ≤ cn lg n for some constant c ≥ 1 cannow be completed by choosing c large enough so that T (2) ≤ c2 lg 2 and T (3) ≤ c3 lg 3. As itturns out, any choice of c ≥ 2 suffices for the base cases of n = 2 and n = 3 to hold. For mostof the recurrences we shall examine, it is straightforward to extend boundary conditions tomake the inductive assumption work for small n.Making a good guessUnfortunately, there is no general way to guess the correct solutions to recurrences. Guessinga solution takes experience and, occasionally, creativity. Fortunately, though, there are someheuristics that can help you become a good guesser. You can also use recursion trees, whichwe shall see in Section 4.2, to generate good guesses.If a recurrence is similar to one you have seen before, then guessing a similar solution isreasonable. As an example, consider the recurrenceT (n) = 2T (⌊n/2⌋ + 17) + n ,which looks difficult because of the added "17" in the argument to T on the right-hand side.Intuitively, however, this additional term cannot substantially affect the solution to therecurrence. When n is large, the difference between T (⌊n/2⌋) and T (⌊n/2⌋ + 17) is not thatlarge: both cut n nearly evenly in half. Consequently, we make the guess that T (n) = O(n lgn), which you can verify as correct by using the substitution method (see Exercise 4.1-5).Another way to make a good guess is to prove loose upper and lower bounds on therecurrence and then reduce the range of uncertainty. For example, we might start with a lowerbound of T (n) = Ω(n) for the recurrence (4.4), since we have the term n in the recurrence, andwe can prove an initial upper bound of T (n) = O(n2). Then, we can gradually lower the upperbound and raise the lower bound until we converge on the correct, asymptotically tightsolution of T (n) = Θ(n lg n).SubtletiesThere are times when you can correctly guess at an asymptotic bound on the solution of arecurrence, but somehow the math doesnt seem to work out in the induction. Usually, the
  • 61. problem is that the inductive assumption isnt strong enough to prove the detailed bound.When you hit such a snag, revising the guess by subtracting a lower-order term often permitsthe math to go through.Consider the recurrenceT (n) = T (⌊n/2⌋) + T (⌈n/2⌉) + 1.We guess that the solution is O(n), and we try to show that T (n) ≤ cn for an appropriatechoice of the constant c. Substituting our guess in the recurrence, we obtainT (n) ≤ c ⌊n/2⌋ + c ⌈n/2⌉ + 1 = cn + 1 ,which does not imply T (n) ≤ cn for any choice of c. Its tempting to try a larger guess, say T(n) = O(n2), which can be made to work, but in fact, our guess that the solution is T (n) = O(n)is correct. In order to show this, however, we must make a stronger inductive hypothesis.Intuitively, our guess is nearly right: were only off by the constant 1, a lower-order term.Nevertheless, mathematical induction doesnt work unless we prove the exact form of theinductive hypothesis. We overcome our difficulty by subtracting a lower-order term from ourprevious guess. Our new guess is T (n) ≤ cn - b, where b ≥ 0 is constant. We now haveT (n) ≤ (c ⌊n/2⌋ - b) + (c ⌈n/2⌉ - b) + 1 = cn - 2b + 1 ≤ cn - b ,as long as b ≥ 1. As before, the constant c must be chosen large enough to handle theboundary conditions.Most people find the idea of subtracting a lower-order term counterintuitive. After all, if themath doesnt work out, shouldnt we be increasing our guess? The key to understanding thisstep is to remember that we are using mathematical induction: we can prove somethingstronger for a given value by assuming something stronger for smaller values.Avoiding pitfallsIt is easy to err in the use of asymptotic notation. For example, in the recurrence (4.4) we canfalsely "prove" T (n) = O(n) by guessing T (n) ≤ cn and then arguingT (n) ≤ 2(c ⌊n/2⌋) + n ≤ cn + n = O(n) , ⇐wrong!!since c is a constant. The error is that we havent proved the exact form of the inductivehypothesis, that is, that T (n) ≤ cn.
  • 62. Changing variablesSometimes, a little algebraic manipulation can make an unknown recurrence similar to oneyou have seen before. As an example, consider the recurrencewhich looks difficult. We can simplify this recurrence, though, with a change of variables. Forconvenience, we shall not worry about rounding off values, such as , to be integers.Renaming m = lg n yieldsT (2m) = 2T (2m/2) + m.We can now rename S(m) = T(2m) to produce the new recurrenceS(m) = 2S(m/2) + m,which is very much like recurrence (4.4). Indeed, this new recurrence has the same solution:S(m) = O(m lg m). Changing back from S(m) to T (n), we obtain T (n) = T (2m) = S(m) = O(mlg m) = O(lg n lg lg n).Exercises 4.1-1Show that the solution of T (n) = T (⌈n/2⌉) + 1 is O(lg n).Exercises 4.1-2We saw that the solution of T (n) = 2T (⌊n/2⌋) + n is O(n lg n). Show that the solution of thisrecurrence is also Ω(n lg n). Conclude that the solution is Θ(n lg n).Exercises 4.1-3Show that by making a different inductive hypothesis, we can overcome the difficulty withthe boundary condition T (1) = 1 for the recurrence (4.4) without adjusting the boundaryconditions for the inductive proof.Exercises 4.1-4Show that Θ(n lg n) is the solution to the "exact" recurrence (4.2) for merge sort.
  • 63. Exercises 4.1-5Show that the solution to T (n) = 2T (⌊n/2⌋ + 17) + n is O(n lg n).Exercises 4.1-6Solve the recurrence by making a change of variables. Your solution should beasymptotically tight. Do not worry about whether values are integral.4.2 The recursion-tree methodAlthough the substitution method can provide a succinct proof that a solution to a recurrenceis correct, it is sometimes difficult to come up with a good guess. Drawing out a recursiontree, as we did in our analysis of the merge sort recurrence in Section 2.3.2, is astraightforward way to devise a good guess. In a recursion tree, each node represents the costof a single subproblem somewhere in the set of recursive function invocations. We sum thecosts within each level of the tree to obtain a set of per-level costs, and then we sum all theper-level costs to determine the total cost of all levels of the recursion. Recursion trees areparticularly useful when the recurrence describes the running time of a divide-and-conqueralgorithm.A recursion tree is best used to generate a good guess, which is then verified by thesubstitution method. When using a recursion tree to generate a good guess, you can oftentolerate a small amount of "sloppiness," since you will be verifying your guess later on. If youare very careful when drawing out a recursion tree and summing the costs, however, you canuse a recursion tree as a direct proof of a solution to a recurrence. In this section, we will userecursion trees to generate good guesses, and in Section 4.4, we will use recursion treesdirectly to prove the theorem that forms the basis of the master method.For example, let us see how a recursion tree would provide a good guess for the recurrence T(n) = 3T (⌊n/4⌋) + Θ(n2). We start by focusing on finding an upper bound for the solution.Because we know that floors and ceilings are usually insubstantial in solving recurrences(heres an example of sloppiness that we can tolerate), we create a recursion tree for therecurrence T (n) = 3T(n/4) + cn2, having written out the implied constant coefficient c > 0.Figure 4.1 shows the derivation of the recursion tree for T (n) = 3T (n/4) + cn2. Forconvenience, we assume that n is an exact power of 4 (another example of tolerablesloppiness). Part (a) of the figure shows T (n), which is expanded in part (b) into an equivalenttree representing the recurrence. The cn2 term at the root represents the cost at the top level ofrecursion, and the three subtrees of the root represent the costs incurred by the subproblems ofsize n/4. Part (c) shows this process carried one step further by expanding each node with costT (n/4) from part (b). The cost for each of the three children of the root is c(n/4)2. We continue
  • 64. expanding each node in the tree by breaking it into its constituent parts as determined by therecurrence.Figure 4.1: The construction of a recursion tree for the recurrence T(n) = 3T(n/4) + cn2. Part(a) shows T(n), which is progressively expanded in (b)-(d) to form the recursion tree. Thefully expanded tree in part (d) has height log4 n (it has log4 n + 1 levels).Because subproblem sizes decrease as we get further from the root, we eventually must reacha boundary condition. How far from the root do we reach one? The subproblem size for anode at depth i is n/4i. Thus, the subproblem size hits n = 1 when n/4i = 1 or, equivalently,when i = log4 n. Thus, the tree has log 4n + 1 levels (0, 1, 2,..., log4 n).Next we determine the cost at each level of the tree. Each level has three times more nodesthan the level above, and so the number of nodes at depth i is 3i. Because subproblem sizesreduce by a factor of 4 for each level we go down from the root, each node at depth i, for i =0, 1, 2,..., log4 n - 1, has a cost of c(n/4i)2. Multiplying, we see that the total cost over all nodesat depth i, for i = 0, 1, 2,..., log4 n - 1, is 3i c(n/4i)2 = (3/16)i cn2. The last level, at depth log4 n,has nodes, each contributing cost T (1), for a total cost of , which is .Now we add up the costs over all levels to determine the cost for the entire tree:
  • 65. This last formula looks somewhat messy until we realize that we can again take advantage ofsmall amounts of sloppiness and use an infinite decreasing geometric series as an upperbound. Backing up one step and applying equation (A.6), we haveThus, we have derived a guess of T (n) = O(n2) for our original recurrence T (n) = 3T (⌊n/4⌋)+ Θ(n2). In this example, the coefficients of cn2 form a decreasing geometric series and, byequation (A.6), the sum of these coefficients is bounded from above by the constant 16/13.Since the roots contribution to the total cost is cn2, the root contributes a constant fraction ofthe total cost. In other words, the total cost of the tree is dominated by the cost of the root.In fact, if O(n2) is indeed an upper bound for the recurrence (as we shall verify in a moment),then it must be a tight bound. Why? The first recursive call contributes a cost of Θ(n2), and soΩ (n2) must be a lower bound for the recurrence.Now we can use the substitution method to verify that our guess was correct, that is, T (n) =O(n2) is an upper bound for the recurrence T (n) = 3T (⌊n/4⌋)+Θ(n2). We want to show that T(n) ≤ dn2 for some constant d > 0. Using the same constant c > 0 as before, we haveT(n) ≤ 3T(⌊n/4⌋) + cn2 ≤ 3d⌊n/4⌋2 + cn2 ≤ 3d(n/4)2 + cn2 = 3/16 dn2 + cn2 ≤ dn2,where the last step holds as long as d ≥ (16/13)c.As another, more intricate example, Figure 4.2 shows the recursion tree for T (n) = T(n/3) +T(2n/3) + O(n).
  • 66. Figure 4.2: A recursion tree for the recurrence T(n) = T (n/3) + T (2n/3) + cn.(Again, we omit floor and ceiling functions for simplicity.) As before, we let c represent theconstant factor in the O(n) term. When we add the values across the levels of the recursiontree, we get a value of cn for every level. The longest path from the root to a leaf is n →(2/3)n → (2/3)2n → ··· → 1. Since (2/3)kn = 1 when k = log3/2 n, the height of the tree is log3/2n.Intuitively, we expect the solution to the recurrence to be at most the number of levels timesthe cost of each level, or O(cn log3/2 n) = O(n lg n). The total cost is evenly distributedthroughout the levels of the recursion tree. There is a complication here: we have yet toconsider the cost of the leaves. If this recursion tree were a complete binary tree of heightlog3/2 n, there would be leaves. Since the cost of each leaf is a constant, the totalcost of all leaves would then be , which is ω(n lg n). This recursion tree is not acomplete binary tree, however, and so it has fewer than leaves. Moreover, as we go downfrom the root, more and more internal nodes are absent. Consequently, not all levelscontribute a cost of exactly cn; levels toward the bottom contribute less. We could work outan accurate accounting of all costs, but remember that we are just trying to come up with aguess to use in the substitution method. Let us tolerate the sloppiness and attempt to show thata guess of O(n lg n) for the upper bound is correct.Indeed, we can use the substitution method to verify that O(n lg n) is an upper bound for thesolution to the recurrence. We show that T (n) ≤ dn lg n, where d is a suitable positiveconstant. We haveT(n) ≤ T(n/3) + T(2n/3) + cn ≤ d(n/3)lg(n/3) + d(2n/3)lg(2n/3) + cn = (d(n/3)lgn - d(n/3)lg 3) + (d(2n/3) lg n - d(2n/3)lg(3/2)) + cn = dn lg n - d((n/3) lg 3 + (2n/3) lg(3/2)) + cn = dn lg n - d((n/3) lg 3 + (2n/3) lg 3 - (2n/3)lg 2) + cn = dn lg n - dn(lg 3 - 2/3) + cn ≤ dn lg n,as long as d ≥ c/(lg 3 - (2/3)). Thus, we did not have to perform a more accurate accounting ofcosts in the recursion tree.Exercises 4.2-1
  • 67. Use a recursion tree to determine a good asymptotic upper bound on the recurrence T(n) =3T(⌊n/2⌋) + n. Use the substitution method to verify your answer.Exercises 4.2-2Argue that the solution to the recurrence T (n) = T (n/3) + T (2n/3) + cn, where c is a constant,is Ω(n lg n) by appealing to a recursion tree.Exercises 4.2-3Draw the recursion tree for T (n) = 4T (⌊n/2⌋)+cn, where c is a constant, and provide a tightasymptotic bound on its solution. Verify your bound by the substitution method.Exercises 4.2-4Use a recursion tree to give an asymptotically tight solution to the recurrence T(n) = T(n - a) +T(a) + cn, where a ≥ 1 and c > 0 are constants.Exercises 4.2-5Use a recursion tree to give an asymptotically tight solution to the recurrence T(n) = T(αn) +T((1 - α)n) + cn, where α is a constant in the range 0 <α < 1 and c > 0 is also a constant.4.3 The master methodThe master method provides a "cookbook" method for solving recurrences of the form(4.5)where a ≥ 1 and b > 1 are constants and f (n) is an asymptotically positive function. Themaster method requires memorization of three cases, but then the solution of manyrecurrences can be determined quite easily, often without pencil and paper.The recurrence (4.5) describes the running time of an algorithm that divides a problem of sizen into a subproblems, each of size n/b, where a and b are positive constants. The a
  • 68. subproblems are solved recursively, each in time T (n/b). The cost of dividing the problemand combining the results of the subproblems is described by the function f (n). (That is, usingthe notation from Section 2.3.2, f(n) = D(n)+C(n).) For example, the recurrence arising fromthe MERGE-SORT procedure has a = 2, b = 2, and f (n) = Θ(n).As a matter of technical correctness, the recurrence isnt actually well defined because n/bmight not be an integer. Replacing each of the a terms T (n/b) with either T (⌊n/b⌋) or T(⌈n/b⌉) doesnt affect the asymptotic behavior of the recurrence, however. (Well prove this inthe next section.) We normally find it convenient, therefore, to omit the floor and ceilingfunctions when writing divide-and-conquer recurrences of this form.The master theoremThe master method depends on the following theorem.Theorem 4.1: (Master theorem)Let a ≥ 1 and b > 1 be constants, let f (n) be a function, and let T (n) be defined on thenonnegative integers by the recurrenceT(n) = aT(n/b) + f(n),where we interpret n/b to mean either ⌊n/b⌋ or ⌈n/b⌉. Then T (n) can be boundedasymptotically as follows. 1. If for some constant > 0, then 2. If , then . 3. If for some constant > 0, and if a f (n/b) ≤ cf (n) for some constant c < 1 and all sufficiently large n, then T (n) = Θ(f (n)).Before applying the master theorem to some examples, lets spend a moment trying tounderstand what it says. In each of the three cases, we are comparing the function f (n) withthe function . Intuitively, the solution to the recurrence is determined by the larger of thetwo functions. If, as in case 1, the function is the larger, then the solution is .If, as in case 3, the function f (n) is the larger, then the solution is T (n) = Θ(f (n)). If, as incase 2, the two functions are the same size, we multiply by a logarithmic factor, and thesolution is .Beyond this intuition, there are some technicalities that must be understood. In the first case,not only must f (n) be smaller than , it must be polynomially smaller. That is, f (n) must beasymptotically smaller than by a factor of n for some constant > 0. In the third case,not only must f (n) be larger than , it must be polynomially larger and in addition satisfythe "regularity" condition that af (n/b) ≤ cf(n). This condition is satisfied by most of thepolynomially bounded functions that we shall encounter.
  • 69. It is important to realize that the three cases do not cover all the possibilities for f (n). There isa gap between cases 1 and 2 when f (n) is smaller than but not polynomially smaller.Similarly, there is a gap between cases 2 and 3 when f (n) is larger than but notpolynomially larger. If the function f (n) falls into one of these gaps, or if the regularitycondition in case 3 fails to hold, the master method cannot be used to solve the recurrence.Using the master methodTo use the master method, we simply determine which case (if any) of the master theoremapplies and write down the answer.As a first example, considerT (n) = 9T(n/3) + n.For this recurrence, we have a = 9, b = 3, f (n) = n, and thus we have that .Since , where = 1, we can apply case 1 of the master theorem and concludethat the solution is T (n) = Θ(n2).Now considerT (n) = T (2n/3) + 1,in which a = 1, b = 3/2, f (n) = 1, and . Case 2 applies, since , and thus the solution to the recurrence is T(n) = Θ(lg n).For the recurrenceT(n) = 3T(n/4) + n lg n,we have a = 3, b = 4, f (n) = n lg n, and . Since , where ≈ 0.2, case 3 applies if we can show that the regularity conditionholds for f (n). For sufficiently large n, af (n/b) = 3(n/4)lg(n/4) ≤ (3/4)n lg n = cf (n) for c =3/4. Consequently, by case 3, the solution to the recurrence is T(n) = Θ(nlg n).The master method does not apply to the recurrenceT(n) = 2T(n/2) + n lg n,even though it has the proper form: a = 2, b = 2, f(n) = n lg n, and . It might seem thatcase 3 should apply, since f (n) = n lg n is asymptotically larger than . The problem isthat it is not polynomially larger. The ratio is asymptotically less thann for any positive constant . Consequently, the recurrence falls into the gap between case 2and case 3. (See Exercise 4.4-2 for a solution.)Exercises 4.3-1Use the master method to give tight asymptotic bounds for the following recurrences.
  • 70. a. T (n) = 4T(n/2) + n. b. T (n) = 4T(n/2) + n2. c. T (n) = 4T(n/2) + n3.Exercises 4.3-2The recurrence T(n) = 7T (n/2)+n2 describes the running time of an algorithm A. A competingalgorithm A′ has a running time of T′(n) = aT′(n/4) + n2. What is the largest integer value for asuch that A′ is asymptotically faster than A?Exercises 4.3-3Use the master method to show that the solution to the binary-search recurrence T(n) = T (n/2)+ Θ(1) is T(n) = Θ(lg n). (See Exercise 2.3-5 for a description of binary search.)Exercises 4.3-4Can the master method be applied to the recurrence T (n) = 4T(n/2) + n2 lg n? Why or whynot? Give an asymptotic upper bound for this recurrence.Exercises 4.3-5:Consider the regularity condition af (n/b) ≤ cf(n) for some constant c < 1, which is part of case3 of the master theorem. Give an example of constants a ≥ 1 and b > 1 and a function f (n) thatsatisfies all the conditions in case 3 of the master theorem except the regularity condition. 4.4: Proof of the master theoremThis section contains a proof of the master theorem (Theorem 4.1). The proof need not beunderstood in order to apply the theorem.The proof is in two parts. The first part analyzes the "master" recurrence (4.5), under thesimplifying assumption that T(n) is defined only on exact powers of b > 1, that is, for n = 1, b,b2, .. This part gives all the intuition needed to understand why the master theorem is true.The second part shows how the analysis can be extended to all positive integers n and ismerely mathematical technique applied to the problem of handling floors and ceilings.
  • 71. In this section, we shall sometimes abuse our asymptotic notation slightly by using it todescribe the behavior of functions that are defined only over exact powers of b. Recall that thedefinitions of asymptotic notations require that bounds be proved for all sufficiently largenumbers, not just those that are powers of b. Since we could make new asymptotic notationsthat apply to the set {bi : i = 0, 1,...}, instead of the nonnegative integers, this abuse is minor.Nevertheless, we must always be on guard when we are using asymptotic notation over alimited domain so that we do not draw improper conclusions. For example, proving that T (n)= O(n) when n is an exact power of 2 does not guarantee that T (n) = O(n). The function T (n)could be defined asin which case the best upper bound that can be proved is T (n) = O(n2). Because of this sort ofdrastic consequence, we shall never use asymptotic notation over a limited domain withoutmaking it absolutely clear from the context that we are doing so.4.4.1 The proof for exact powersThe first part of the proof of the master theorem analyzes the recurrence (4.5)T (n) = aT (n/b) + f (n) ,for the master method, under the assumption that n is an exact power of b > 1, where b neednot be an integer. The analysis is broken into three lemmas. The first reduces the problem ofsolving the master recurrence to the problem of evaluating an expression that contains asummation. The second determines bounds on this summation. The third lemma puts the firsttwo together to prove a version of the master theorem for the case in which n is an exactpower of b.Lemma 4.2Let a ≥ 1 and b > 1 be constants, and let f (n) be a nonnegative function defined on exactpowers of b. Define T (n) on exact powers of b by the recurrencewhere i is a positive integer. Then(4.6)Proof We use the recursion tree in Figure 4.3. The root of the tree has cost f (n), and it has achildren, each with cost f (n/b). (It is convenient to think of a as being an integer, especiallywhen visualizing the recursion tree, but the mathematics does not require it.) Each of thesechildren has a children with cost f (n/b2), and thus there are a2 nodes that are distance 2 from
  • 72. the root. In general, there are aj nodes that are distance j from the root, and each has cost f(n/bj). The cost of each leaf is T (1) = Θ(1), and each leaf is at depth logb n, since .There are leaves in the tree.Figure 4.3: The recursion tree generated by T (n) = aT (n/b) + f (n). The tree is a complete a-ary tree with leaves and height logb n. The cost of each level is shown at the right, andtheir sum is given in equation (4.6).We can obtain equation (4.6) by summing the costs of each level of the tree, as shown in thefigure. The cost for a level j of internal nodes is aj f(n/bj), and so the total of all internal nodelevels isIn the underlying divide-and-conquer algorithm, this sum represents the costs of dividingproblems into subproblems and then recombining the subproblems. The cost of all the leaves,which is the cost of doing all subproblems of size 1, is .In terms of the recursion tree, the three cases of the master theorem correspond to cases inwhich the total cost of the tree is (1) dominated by the costs in the leaves, (2) evenlydistributed across the levels of the tree, or (3) dominated by the cost of the root.The summation in equation (4.6) describes the cost of the dividing and combining steps in theunderlying divide-and-conquer algorithm. The next lemma provides asymptotic bounds on thesummations growth.Lemma 4.3Let a ≥ 1 and b > 1 be constants, and let f(n) be a nonnegative function defined on exactpowers of b. A function g(n) defined over exact powers of b by
  • 73. (4.7)can then be bounded asymptotically for exact powers of b as follows. 1. If for some constant > 0, then . 2. If , then . 3. If af (n/b) ≤ cf(n) for some constant c < 1 and for all n ≥ b, then g(n) = Θ(f(n)).Proof For case 1, we have , which implies that .Substituting into equation (4.7) yields(4.8)We bound the summation within the O-notation by factoring out terms and simplifying, whichleaves an increasing geometric series:Since b and are constants, we can rewrite the last expression as .Substituting this expression for the summation in equation (4.8) yieldsand case 1 is proved.Under the assumption that for case 2, we have that .Substituting into equation (4.7) yields(4.9)We bound the summation within the Θ as in case 1, but this time we do not obtain a geometricseries. Instead, we discover that every term of the summation is the same:
  • 74. Substituting this expression for the summation in equation (4.9) yieldsg(n) = ( =( ,and case 2 is proved.Case 3 is proved similarly. Since f(n) appears in the definition (4.7) of g(n) and all terms ofg(n) are nonnegative, we can conclude that g(n) = Ω(f(n)) for exact powers of b. Under ourassumption that af(n/b) ≤ cf(n) for some constant c < 1 and all n ≥ b, we have f(n/b) ≤(c/a)f(n). Iterating j times, we have f(n/bj) ≤ (c/a)j f(n) or, equivalently, aj f(n/bj) ≤ cj f(n).Substituting into equation (4.7) and simplifying yields a geometric series, but unlike the seriesin case 1, this one has decreasing terms:since c is constant. Thus, we can conclude that g(n) = Θ(f(n)) for exact powers of b. Case 3 isproved, which completes the proof of the lemma.We can now prove a version of the master theorem for the case in which n is an exact powerof b.Lemma 4.4Let a ≥ 1 and b > 1 be constants, and let f(n) be a nonnegative function defined on exactpowers of b. Define T(n) on exact powers of b by the recurrence
  • 75. where i is a positive integer. Then T(n) can be bounded asymptotically for exact powers of bas follows. 1. If for some constant > 0, then . 2. If , then . 3. If for some constant > 0, and if af (n/b) ≤ cf(n) for some constant c < 1 and all sufficiently large n, then T(n) = Θ(f(n)).Proof We use the bounds in Lemma 4.3 to evaluate the summation (4.6) from Lemma 4.2.For case 1, we haveT(n) = = ,and for case 2,T(n) = = .For case 3,T(n) = = Θ(f(n)),because .4.4.2 Floors and ceilingsTo complete the proof of the master theorem, we must now extend our analysis to thesituation in which floors and ceilings are used in the master recurrence, so that the recurrenceis defined for all integers, not just exact powers of b. Obtaining a lower bound on(4.10)and an upper bound on(4.11)is routine, since the bound ⌈n/b⌉ ≥ n/b can be pushed through in the first case to yield thedesired result, and the bound ⌊n/b⌋ ≤ n/b can be pushed through in the second case. Lowerbounding the recurrence (4.11) requires much the same technique as upper bounding therecurrence (4.10), so we shall present only this latter bound.
  • 76. We modify the recursion tree of Figure 4.3 to produce the recursion tree in Figure 4.4. As wego down in the recursion tree, we obtain a sequence of recursive invocations on the argumentsFigure 4.4: The recursion tree generated by T(n) = aT(⌈n/b⌉) + f(n). The recursive argumentnj is given by equation (4.12).n ,⌈n/b⌉ ,⌈⌈n/b⌉/b⌉ ,⌈⌈⌈n/b⌉/b⌉/b⌉ , ⋮Let us denote the jth element in the sequence by nj, where(4.12)Our first goal is to determine the depth k such that nk is a constant. Using the inequality ⌈x⌉ ≤x + 1, we obtainIn general,
  • 77. Letting j = ⌊logb n⌋, we obtainand thus we see that at depth ⌊logb n⌋, the problem size is at most a constant.From Figure 4.4, we see that(4.13)which is much the same as equation (4.6), except that n is an arbitrary integer and notrestricted to be an exact power of b.We can now evaluate the summation(4.14)from (4.13) in a manner analogous to the proof of Lemma 4.3. Beginning with case 3, ifaf(⌈n/b⌉) ≤ cf(n) for n > b + b/(b - 1), where c < 1 is a constant, then it follows that ajf(nj) ≤cjf(n). Therefore, the sum in equation (4.14) can be evaluated just as in Lemma 4.3. For case2, we have . If we can show that , then the proof forcase 2 of Lemma 4.3 will go through. Observe that j = ≤ ⌊logb n⌋ implies bj/n ≤ 1. The bound implies that there exists a constant c > 0 such that for all sufficiently large nj,
  • 78. since is a constant. Thus, case 2 is proved. The proof of case 1 is almostidentical. The key is to prove the bound , which is similar to the correspondingproof of case 2, though the algebra is more intricate.We have now proved the upper bounds in the master theorem for all integers n. The proof ofthe lower bounds is similar.Exercises 4.4-1:Give a simple and exact expression for nj in equation (4.12) for the case in which b is apositive integer instead of an arbitrary real number.Exercises 4.4-2:Show that if , where k ≥ 0, then the master recurrence has solution . For simplicity, confine your analysis to exact powers of b.Exercises 4.4-3:Show that case 3 of the master theorem is overstated, in the sense that the regularity conditionaf(n/b) ≤ cf(n) for some constant c < 1 implies that there exists a constant > 0 such that .Problems 4-1: Recurrence examplesGive asymptotic upper and lower bounds for T(n) in each of the following recurrences.Assume that T(n) is constant for n ≤ 2. Make your bounds as tight as possible, and justify youranswers. a. T(n) = 2T(n/2) + n3. b. T(n) = T(9n/10) + n. c. T(n) = 16T(n/4) + n2. d. T (n) = 7T(n/3) + n2. e. T(n) = 7T(n/2) + n2. f. . g. T(n) = T(n - 1) + n. h. .
  • 79. Problems 4-2: Finding the missing integerAn array A[1 n] contains all the integers from 0 to n except one. It would be easy todetermine the missing integer in O(n) time by using an auxiliary array B[0 n] to recordwhich numbers appear in A. In this problem, however, we cannot access an entire integer in Awith a single operation. The elements of A are represented in binary, and the only operationwe can use to access them is "fetch the jth bit of A[i]," which takes constant time.Show that if we use only this operation, we can still determine the missing integer in O(n)time.Problems 4-3: Parameter-passing costsThroughout this book, we assume that parameter passing during procedure calls takesconstant time, even if an N-element array is being passed. This assumption is valid in mostsystems because a pointer to the array is passed, not the array itself. This problem examinesthe implications of three parameter-passing strategies: 1. An array is passed by pointer. Time = Θ(1). 2. An array is passed by copying. Time = Θ(N), where N is the size of the array. 3. An array is passed by copying only the subrange that might be accessed by the called procedure. Time = Θ(q - p + 1) if the subarray A[p q] is passed. a. Consider the recursive binary search algorithm for finding a number in a sorted array (see Exercise 2.3-5). Give recurrences for the worst-case running times of binary search when arrays are passed using each of the three methods above, and give good upper bounds on the solutions of the recurrences. Let N be the size of the original problem and n be the size of a subproblem. b. Redo part (a) for the MERGE-SORT algorithm from Section 2.3.1.Problems 4-4: More recurrence examplesGive asymptotic upper and lower bounds for T(n) in each of the following recurrences.Assume that T(n) is constant for sufficiently small n. Make your bounds as tight as possible,and justify your answers. a. T(n) = 3T(n/2) + n lg n. b. T(n) = 5T(n/5) + n/ lg n. c. d. T(n) = 3T(n/3 + 5) + n/2. e. T(n) = 2T(n/2) + n/ lg n. f. T(n) = T(n/2) + T(n/4) + T(n/8) + n. g. T(n) = T(n - 1) + 1/n.
  • 80. h. T(n) = T(n - 1) + lg n. i. T(n) = T(n - 2) + 2 lg n. j. .Problems 4-5: Fibonacci numbersThis problem develops properties of the Fibonacci numbers, which are defined by recurrence(3.21). We shall use the technique of generating functions to solve the Fibonacci recurrence.Define the generating function (or formal power series) F aswhere Fi is the ith Fibonacci number. a. Show that F (z) = z + z F (z) + z2F(z). b. Show that where and c. Show that d. Prove that for i > 0, rounded to the nearest integer. (Hint: Observe .) e. Prove that Fi+2 ≥ φi for i ≥ 0.Problems 4-6: VLSI chip testing
  • 81. Professor Diogenes has n supposedly identical VLSI[1] chips that in principle are capable oftesting each other. The professors test jig accommodates two chips at a time. When the jig isloaded, each chip tests the other and reports whether it is good or bad. A good chip alwaysreports accurately whether the other chip is good or bad, but the answer of a bad chip cannotbe trusted. Thus, the four possible outcomes of a test are as follows:Chip A says Chip B says ConclusionB is good A is good both are good, or both are badB is good A is bad at least one is badB is bad A is good at least one is badB is bad A is bad at least one is bad a. Show that if more than n/2 chips are bad, the professor cannot necessarily determine which chips are good using any strategy based on this kind of pairwise test. Assume that the bad chips can conspire to fool the professor. b. Consider the problem of finding a single good chip from among n chips, assuming that more than n/2 of the chips are good. Show that ⌊n/2⌋ pairwise tests are sufficient to reduce the problem to one of nearly half the size. c. Show that the good chips can be identified with Θ(n) pairwise tests, assuming that more than n/2 of the chips are good. Give and solve the recurrence that describes the number of tests.Problems 4-7: Monge arraysAn m × n array A of real numbers is a Monge array if for all i, j, k, and l such that 1 ≤ i < k ≤m and 1 ≤ j < l ≤ n, we haveA[i, j] + A[k, l]