id
int64
0
25.6k
text
stringlengths
0
4.59k
20,100
chap mathematical preliminaries thought processwhich in turn clarifies your explanations secondif you use one of the standard proof structures such as proof by contradiction or an induction proofthen both you and your reader are working from shared understanding of that structure that makes for less complexity to your reader to understand your proofbecause the reader need not decode the structure of your argument from scratch this section briefly introduces three commonly used proof techniques(ideductionor direct proof(iiproof by contradictionand (iiiproof by mathematical induction direct proof in generala direct proof is just "logical explanation direct proof is sometimes referred to as an argument by deduction this is simply an argument in terms of logic often written in english with words such as "if then,it could also be written with logic notation such as " even if we don' wish to use symbolic logic notationwe can still take advantage of fundamental theorems of logic to structure our arguments for exampleif we want to prove that and are equivalentwe can first prove and then prove in some domainsproofs are essentially series of state changes from start state to an end state formal predicate logic can be viewed in this waywith the various "rules of logicbeing used to make the changes from one formula or combining couple of formulas to make new formula on the route to the destination symbolic manipulations to solve integration problems in introductory calculus classes are similar in spiritas are high school geometry proofs proof by contradiction the simplest way to disprove theorem or statement is to find counterexample to the theorem unfortunatelyno number of examples supporting theorem is sufficient to prove that the theorem is correct howeverthere is an approach that is vaguely similar to disproving by counterexamplecalled proof by contradiction to prove theorem by contradictionwe first assume that the theorem is false we then find logical contradiction stemming from this assumption if the logic used to find the contradiction is correctthen the only way to resolve the contradiction is to recognize that the assumption that the theorem is false must be incorrect that iswe conclude that the theorem must be true example here is simple proof by contradiction theorem there is no largest integer
20,101
proofproof by contradiction step contrary assumptionassume that there is largest integer call it (for "biggest"step show this assumption leads to contradictionconsider is an integer because it is the sum of two integers alsoc bwhich means that is not the largest integer after all thuswe have reached contradiction the only flaw in our reasoning is the initial assumption that the theorem is false thuswe conclude that the theorem is correct related proof technique is proving the contrapositive we can prove that by proving (not (not proof by mathematical induction mathematical induction is much like recursion it is applicable to wide variety of theorems induction also provides useful way to think about algorithm designbecause it encourages you to think about solving problem by building up from simple subproblems induction can help to prove that recursive function produces the correct result within the context of algorithm analysisone of the most important uses for mathematical induction is as method to test hypothesis as explained in section when seeking closed-form solution for summation or recurrence we might first guess or otherwise acquire evidence that particular formula is the correct solution if the formula is indeed correctit is often an easy matter to prove that fact with an induction proof let thrm be theorem to proveand express thrm in terms of positive integer parameter mathematical induction states that thrm is true for any value of parameter (for >cwhere is some constantif the following two conditions are true base casethrm holds for cand induction stepif thrm holds for then thrm holds for proving the base case is usually easytypically requiring that some small value such as be substituted for in the theorem and applying simple algebra or logic as necessary to verify the theorem proving the induction step is sometimes easyand sometimes difficult an alternative formulation of the induction step is known as strong induction the induction step for strong induction is induction stepif thrm holds for all kc < nthen thrm holds for
20,102
chap mathematical preliminaries proving either variant of the induction step (in conjunction with verifying the base caseyields satisfactory proof by mathematical induction the two conditions that make up the induction proof combine to demonstrate that thrm holds for as an extension of the fact that thrm holds for this factcombined again with condition ( or ( )indicates that thrm also holds for and so on thusthrm holds for all values of (larger than the base casesonce the two conditions have been proved what makes mathematical induction so powerful (and so mystifying to most people at firstis that we can take advantage of the assumption that thrm holds for all values less than to help us prove that thrm holds for this is known as the induction hypothesis having this assumption to work with makes the induction step easier to prove than tackling the original theorem itself being able to rely on the induction hypothesis provides extra information that we can bring to bear on the problem there are important similarities between recursion and induction both are anchored on one or more base cases recursive function relies on the ability to call itself to get the answer for smaller instances of the problem likewiseinduction proofs rely on the truth of the induction hypothesis to prove the theorem the induction hypothesis does not come out of thin air it is true if and only if the theorem itself is trueand therefore is reliable within the proof context using the induction hypothesis it do work is exactly the same as using recursive call to do work example here is sample proof by mathematical induction call the sum of the first positive integers (ntheorem (nn( )/ proofthe proof is by mathematical induction check the base case for verify that ( ( )/ ( is simply the sum of the first positive numberwhich is because ( )/ the formula is correct for the base case state the induction hypothesis the induction hypothesis is ( - = ( )(( ( )( use the assumption from the induction hypothesis for to show that the result is true for the induction hypothesis states
20,103
sec mathematical proof techniques that ( ( )( )/ and because (ns( nwe can substitute for ( to get - = +ni= ( )( + ( thusby mathematical inductions(nn ( )/ = note carefully what took place in this example first we cast (nin terms of smaller occurrence of the problems(ns( this is important because once ( comes into the picturewe can use the induction hypothesis to replace ( )with ( )( )/ from hereit is simple algebra to prove that ( equals the right-hand side of the original theorem example here is another simple proof by induction that illustrates choosing the proper variable for induction we wish to prove by induction that the sum of the first positive odd numbers is first we need way to describe the nth odd numberwhich is simply this also allows us to cast the theorem as summation pn theorem = ( proofthe base case of yields which is true the induction hypothesis is - ( ( ) = we now use the induction hypothesis to show that the theorem holds true for the sum of the first odd numbers is simply the sum of the first odd numbers plus the nth odd number in the second line belowwe will use the induction hypothesis to replace the partial summation (shown in brackets in the first linewith its closed-form solution after thatalgebra
20,104
chap mathematical preliminaries takes care of the rest " - ( ( = = ( ) thusby mathematical inductionpn = ( example this example shows how we can use induction to prove that proposed closed-form solution for recurrence relation is correct theorem the recurrence relation (nt( - )+ ( has closed-form solution (nn proofto prove the base casewe observe that ( the induction hypothesis is that ( combining the definition of the recurrence with the induction hypothesiswe see immediately that (nt( for thuswe have proved the theorem correct by mathematical induction example this example uses induction without involving summations or other equations it also illustrates more flexible use of base cases theorem cand cstamps can be used to form any value (for values > proofthe theorem defines the problem for values > because it does not hold for the values and using as the base casea value of ccan be made from two cstamps the induction hypothesis is that value of can be made from some combination of cand cstamps we now use the induction hypothesis to show how to get the value from cand cstamps either the makeup for value includes cstampor it does not if so
20,105
then replace cstamp with three cstamps if notthen the makeup must have included at least two cstamps (because it is at least of size and contains only cstampsin this casereplace two of the cstamps with single cstamp in either casewe now have value of made up of cand cstamps thusby mathematical inductionthe theorem is correct example here is an example using strong induction theorem for is divisible by some prime number prooffor the base casechoose is divisible by the prime number the induction hypothesis is that any value < nis divisible by some prime number there are now two cases to consider when proving the theorem for if is prime numberthen is divisible by itself if is not prime numberthen for and bboth integers less than but greater than the induction hypothesis tells us that is divisible by some prime number that same prime number must also divide thusby mathematical inductionthe theorem is correct our next example of mathematical induction proves theorem from geometry it also illustrates standard technique of induction proof where we take objects and remove some object to use the induction hypothesis example define two-coloring for set of regions as way of assigning one of two colors to each region such that no two regions sharing side have the same color for examplea chessboard is two-colored figure shows two-coloring for the plane with three lines we will assume that the two colors to be used are black and white theorem the set of regions formed by infinite lines in the plane can be two-colored proofconsider the base case of single infinite line in the plane this line splits the plane into two regions one region can be colored black and the other white to get valid two-coloring the induction hypothesis is that the set of regions formed by infinite lines can be two-colored to prove the theorem for nconsider the set of regions formed by the lines remaining when any one of the lines is removed by the induction hypothesisthis set of regions can be two-colored nowput the nth line back this splits the plane into two half-planeseach of which (independentlyhas valid two-coloring inherited from the two-coloring of the plane with
20,106
chap mathematical preliminaries figure two-coloring for the regions formed by three lines in the plane lines unfortunatelythe regions newly split by the nth line violate the rule for two-coloring take all regions on one side of the nth line and reverse their coloring (after doing sothis half-plane is still two-coloredthose regions split by the nth line are now properly two-coloredbecause the part of the region to one side of the line is now black and the region to the other side is now white thusby mathematical inductionthe entire plane is two-colored compare the proof of theorem with that of theorem for theorem we took collection of stamps of size (whichby the induction hypothesismust have the desired propertyand from that "builta collection of size that has the desired property we therefore proved the existence of some collection of stamps of size with the desired property for theorem we must prove that any collection of lines has the desired property thusour strategy is to take an arbitrary collection of linesand "reduceit so that we have set of lines that must have the desired property because it matches the induction hypothesis from therewe merely need to show that reversing the original reduction process preserves the desired property in contrastconsider what would be required if we attempted to "buildfrom set of lines of size to one of size we would have great difficulty justifying that all possible collections of lines are covered by our building process by reducing from an arbitrary collection of lines to something lesswe avoid this problem this section' final example shows how induction can be used to prove that recursive function produces the correct result
20,107
example we would like to prove that function fact does indeed compute the factorial function there are two distinct steps to such proof the first is to prove that the function always terminates the second is to prove that the function returns the correct value theorem function fact will terminate for any value of prooffor the base casewe observe that fact will terminate directly whenever < the induction hypothesis is that fact will terminate for for nwe have two possibilities one possibility is that > in that casefact will terminate directly because it will fail its assertion test otherwisefact will make recursive call to fact( - by the induction hypothesisfact( - must terminate theorem function fact does compute the factorial function for any value in the range to proofto prove the base caseobserve that when or fact(nreturns the correct value of the induction hypothesis is that fact( - returns the correct value of ( )for any value within the legal rangefact(nreturns fact( - by the induction hypothesisfact( - ( )!and because ( ) !we have proved that fact(nproduces the correct result we can use similar process to prove many recursive programs correct the general form is to show that the base cases perform correctlyand then to use the induction hypothesis to show that the recursive step also produces the correct result prior to thiswe must prove that the function always terminateswhich might also be done using an induction proof estimating one of the most useful life skills that you can gain from your computer science training is knowing how to perform quick estimates this is sometimes known as "back of the napkinor "back of the envelopecalculation both nicknames suggest that only rough estimate is produced estimation techniques are standard part of engineering curricula but are often neglected in computer science estimation is no substitute for rigorousdetailed analysis of problembut it can serve to indicate when rigorous analysis is warrantedif the initial estimate indicates that the solution is unworkablethen further analysis is probably unnecessary estimating can be formalized by the following three-step process determine the major parameters that affect the problem
20,108
chap mathematical preliminaries derive an equation that relates the parameters to the problem select values for the parametersand apply the equation to yield an estimated solution when doing estimationsa good way to reassure yourself that the estimate is reasonable is to do it in two different ways in generalif you want to know what comes out of systemyou can either try to estimate that directlyor you can estimate what goes into the system (assuming that what goes in must later come outif both approaches (independentlygive similar answersthen this should build confidence in the estimate when calculatingbe sure that your units match for exampledo not add feet and pounds verify that the result is in the correct units always keep in mind that the output of calculation is only as good as its input the more uncertain your valuation for the input parameters in step the more uncertain the output value howeverback of the envelope calculations are often meant only to get an answer within an order of magnitudeor perhaps within factor of two before doing an estimateyou should decide on acceptable error boundssuch as within %within factor of twoand so forth once you are confident that an estimate falls within your error boundsleave it alonedo not try to get more precise estimate than necessary for your purpose example how many library bookcases does it take to store books containing one million pagesi estimate that -page book requires one inch on the library shelf (for examplelook at the size of this book)yielding about feet of shelf space for one million pages if shelf is feet widethen shelves are required if bookcase contains shelvesthis yields about library bookcases to reach this conclusioni estimated the number of pages per inchthe width of shelfand the number of shelves in bookcase none of my estimates are likely to be precisebut feel confident that my answer is correct to within factor of two (after writing thisi went to virginia tech' library and looked at some real bookcases they were only about feet widebut typically had shelves for total of shelf-feet so was correct to within on bookcase capacityfar better than expected or needed one of my selected values was too highand the other too lowwhich canceled out the errors example is it more economical to buy car that gets miles per gallonor one that gets miles per gallon but costs $ morethe
20,109
typical car is driven about , miles per year if gasoline costs $ /gallonthen the yearly gas bill is $ for the less efficient car and $ for the more efficient car if we ignore issues such as the payback that would be received if we invested $ in bankit would take years to make up the difference in price at this pointthe buyer must decide if price is the only criterion and if -year payback time is acceptable naturallya person who drives more will make up the difference more quicklyand changes in gasoline prices will also greatly affect the outcome example when at the supermarket doing the week' shoppingcan you estimate about how much you will have to pay at the checkoutone simple way is to round the price of each item to the nearest dollarand add this value to mental running total as you put the item in your shopping cart this will likely give an answer within couple of dollars of the true total further reading most of the topics covered in this are considered part of discrete mathematics an introduction to this field is discrete mathematics with applications by susanna epp [epp an advanced treatment of many mathematical topics useful to computer scientists is concrete mathematicsa foundation for computer science by grahamknuthand patashnik [gkp see "technically speakingfrom the february issue of ieee spectrum [sel for discussion on the standard for indicating units of computer storage used in this book introduction to algorithms by udi manber [man makes extensive use of mathematical induction as technique for developing algorithms for more information on recursionsee thinking recursively by eric roberts [rob to learn recursion properlyit is worth your while to learn the programming language lispeven if you never intend to write lisp program in particularfriedman and felleisen' the little lisper [ff is designed to teach you how to think recursively as well as teach you lisp this book is entertaining reading as well good book on writing mathematical proofs is daniel solow' how to read and do proofs [sol to improve your general mathematical problem-solving abilitiessee the art and craft of problem solving by paul zeitz [zei zeitz
20,110
chap mathematical preliminaries also discusses the three proof techniques presented in section and the roles of investigation and argument in problem solving for more about estimating techniquessee two programming pearls by john louis bentley entitled the back of the envelope and the envelope is back [ben ben ben ben geniusthe life and science of richard feynman by james gleick [gle gives insight into how important back of the envelope calculation was to the developers of the atomic bomband to modern theoretical physics in general exercises for each relation belowexplain why the relation does or does not satisfy each of the properties reflexivesymmetricantisymmetricand transitive ( "isbrotherofon the set of people ( "isfatherofon the set of people (cthe relation {hxyi for real numbers and (dthe relation {hxyi for real numbers and (ethe relation {hxyi mod for xy { (fthe empty relation ( the relation with no ordered pairs for which it is trueon the set of integers (gthe empty relation ( the relation with no ordered pairs for which it is trueon the empty set for each of the following relationseither prove that it is an equivalence relation or prove that it is not an equivalence relation (afor integers and ba if and only if is even (bfor integers and ba if and only if is odd (cfor nonzero rational numbers and ba if and only if (dfor nonzero rational numbers and ba if and only if / is an integer (efor rational numbers and ba if and only if is an integer (ffor rational numbers and ba if and only if | < state whether each of the following relations is partial orderingand explain why or why not ( "isfatherofon the set of people ( "isancestorofon the set of people ( "isolderthanon the set of people ( "issisterofon the set of people ( {habihaaihbaion the set {ab
20,111
( { ih ih ion the set { how many total orderings can be defined on set with elementsexplain your answer define an adt for set of integers (remember that set has no concept of duplicate elementsand has no concept of orderyour adt should consist of the functions that can be performed on set to control its membershipcheck the sizecheck if given element is in the setand so on each function should be defined in terms of its input and output define an adt for bag of integers (remember that bag may contain duplicatesand has no concept of orderyour adt should consist of the functions that can be performed on bag to control its membershipcheck the sizecheck if given element is in the setand so on each function should be defined in terms of its input and output define an adt for sequence of integers (remember that sequence may contain duplicatesand supports the concept of position for its elementsyour adt should consist of the functions that can be performed on sequence to control its membershipcheck the sizecheck if given element is in the setand so on each function should be defined in terms of its input and output an investor places $ , into stock fund years later the account has value of $ , using logarithms and anti-logarithmspresent formula for calculating the average annual rate of increase then use your formula to determine the average annual growth rate for this fund rewrite the factorial function of section without using recursion rewrite the for loop for the random permutation generator of section as recursive function here is simple recursive function to compute the fibonacci sequence/recursive fibonacci generator static long fibr(int /fibr( is the largest value that fits in long assert ( &( < " out of range"if (( = |( = )return /base case return fibr( - fibr( - )/recursive call this algorithm turns out to be very slowcalling fibr total of fib(ntimes contrast this with the following iterative algorithm
20,112
chap mathematical preliminaries /iterative fibonacci generator static long fibi(int /fibr( is the largest value that fits in long assert ( &( < " out of range"long currprevpastif (( = |( = )return curr prev /curr holds current fib value for (int = <=ni++/compute next value past prev/past holds fibi( - prev curr/prev holds fibi( - curr past prev/curr now holds fibi(ireturn currfunction fibi executes the for loop times (awhich version is easier to understandwhy(bexplain why fibr is so much slower than fibi write recursive function to solve generalization of the towers of hanoi problem where each ring may begin on any pole so long as no ring sits on top of smaller ring consider the following functionstatic void foo (double valif (val ! foo(val/ )this function makes progress towards the base case on every recursive call in theory (that isif double variables acted like true real numbers)would this function ever terminate for input val nonzero numberin practice (an actual computer implementation)will it terminate write function to print all of the permutations for the elements of an array containing distinct integer values write recursive algorithm to print all of the subsets for the set of the first positive integers the largest common factor (lcffor two positive integers and is the largest integer that divides both and evenly lcf(nmis at least oneand at most massuming that > over two thousand years agoeuclid provided an efficient algorithm based on the observation thatwhen mod lcf(nmgcd(mn mod muse this fact to write two algorithms to find lcf for two positive integers the first version should compute the value iteratively the second version should compute the value using recursion
20,113
sec exercises prove by contradiction that the number of primes is infinite (ause induction to show that is always even (bgive direct proof in one or two sentences that is always even (cshow that is always divisible by three (dis aways divisible by explain your answer prove that is irrational explain why - ( ( ii= = = prove equation using mathematical induction prove equation using mathematical induction prove equation using mathematical induction find closed-form solution and prove (using inductionthat your solution is correct for the summation = prove that the sum of the first even numbers is (aindirectly by assuming that the sum of the first odd numbers is (bdirectly by mathematical induction give closed-form formula for the summation ni= where is an integer between and prove that fib( ) provefor > that ( ) = the following theorem is called the pigeonhole principle theorem when pigeons roost in holesthere must be some hole containing at least two pigeons (aprove the pigeonhole principle using proof by contradiction (bprove the pigeonhole principle using mathematical induction for this problemyou will consider arrangements of infinite lines in the plane such that three or more lines never intersect at single point (agive recurrence relation that expresses the number of regions formed by linesand explain why your recurrence is correct
20,114
chap mathematical preliminaries (bgive the summation that results from expanding your recurrence (cgive closed-form solution for the summation prove (using inductionthat the recurrence (nt( nt( has as its closed-form solution (nn( )/ expand the following recurrence to help you find closed-form solutionand then use induction to prove your answer is correct ( ( for ( expand the following recurrence to help you find closed-form solutionand then use induction to prove your answer is correct (nt( for ( assume that an -bit integer (represented by standard binary notationtakes any value in the range to with equal probability (afor each bit positionwhat is the probability of its value being and what is the probability of its value being (bwhat is the average number of " bits for an -bit random number(cwhat is the expected value for the position of the leftmost " bitin other wordshow many positions on average must we examine when moving from left to right before encountering " bitshow the appropriate summation what is the total volume of your body in liters (orif you prefergallons) an art historian has database of , full-screen color images (aabout how much space will this requirehow many cd-roms would be required to store the database( cd-rom holds about mb of databe sure to explain all assumptions you made to derive your answer (bnowassume that you have access to good image compression technique that can store the images in only / of the space required for an uncompressed image will the entire database fit onto single cdrom if the images are compressed how many cubic miles of water flow out of the mouth of the mississippi river each daydo not look up the answer or any supplemental facts be sure to describe all assumptions made in arriving at your answer
20,115
when buying home mortgageyou often have the option of paying some money in advance (called "discount points"to get lower interest rate assume that you have the choice between two -year mortgagesone at %and the other at with an up-front charge of of the mortgage value how long would it take to recover the charge when you take the mortgage at the lower rateas secondmore precise estimatehow long would it take to recover the charge plus the interest you would have received if you had invested the equivalent of the charge in the bank at interest while paying the higher ratedo not use calculator to help you answer this question when you build new houseyou sometimes get "construction loanwhich is temporary line of credit out of which you pay construction costs as they occur at the end of the construction periodyou then replace the construction loan with regular mortgage on the house during the construction loanyou only pay each month for the interest charged against the actual amount borrowed so far assume that your house construction project starts at the beginning of apriland is complete at the end of six months assume that the total construction cost will be $ , with the costs occurring at the beginning of each month in $ , increments the construction loan charges interest estimate the total interest payments that must be paid over the life of the construction loan here are some questions that test your working knowledge of how fast computers operate is disk drive access time normally measured in milliseconds (thousandths of secondor microseconds (millionths of second)does your ram memory access word in more or less than one microsecondhow many instructions can your cpu execute in one year if the machine is left running at full speed all the timedo not use paper or calculator to derive your answers does your home contain enough books to total one million pageshow many total pages are stored in your school library building how many words are in this book how many hours are one million secondshow many daysanswer these questions doing all arithmetic in your head how many cities and towns are there in the united states how many steps would it take to walk from boston to san francisco man begins car trip to visit his in-laws the total distance is milesand he starts off at speed of miles per hour after driving exactly milehe loses some of his enthusiasm for the journeyand (instantaneouslyslows
20,116
chap mathematical preliminaries down to miles per hour after traveling another milehe again slows to miles per hour this continuesprogressively slowing by mile per hour for each mile traveled until the trip is complete (ahow long does it take the man to reach his in-laws(bhow long would the trip take in the continuous case where the speed smoothly diminishes with the distance yet to travel
20,117
algorithm analysis how long will it take to process the company payroll once we complete our planned mergershould buy new payroll program from vendor or vendor yif particular program is slowis it badly implemented or is it solving hard problemquestions like these ask us to consider the difficulty of problemor the relative efficiency of two or more approaches to solving problem this introduces the motivationbasic notationand fundamental techniques of algorithm analysis we focus on methodology known as asymptotic algorithm analysisor simply asymptotic analysis asymptotic analysis attempts to estimate the resource consumption of an algorithm it allows us to compare the relative costs of two or more algorithms for solving the same problem asymptotic analysis also gives algorithm designers tool for estimating whether proposed solution is likely to meet the resource constraints for problem before they implement an actual program after reading this you should understand the concept of growth ratethe rate at which the cost of an algorithm grows as the size of its input growsthe concept of upper and lower bounds for growth rateand how to estimate these bounds for simple programalgorithmor problemand the difference between the cost of an algorithm (or programand the cost of problem the concludes with brief discussion of the practical difficulties encountered when empirically measuring the cost of programand some principles for code tuning to improve program efficiency introduction how do you compare two algorithms for solving some problem in terms of efficiencyone way is to implement both algorithms as computer programs and then
20,118
chap algorithm analysis run them on suitable range of inputsmeasuring how much of the resources in question each program uses this approach is often unsatisfactory for four reasons firstthere is the effort involved in programming and testing two algorithms when at best you want to keep only one secondwhen empirically comparing two algorithms there is always the chance that one of the programs was "better writtenthan the otherand that the relative qualities of the underlying algorithms are not truly represented by their implementations this is especially likely to occur when the programmer has bias regarding the algorithms thirdthe choice of empirical test cases might unfairly favor one algorithm fourthyou could find that even the better of the two algorithms does not fall within your resource budget in that case you must begin the entire process again with yet another program implementing new algorithm buthow would you know if any algorithm can meet the resource budgetperhaps the problem is simply too difficult for any implementation to be within budget these problems can often be avoided by using asymptotic analysis asymptotic analysis measures the efficiency of an algorithmor its implementation as programas the input size becomes large it is actually an estimating technique and does not tell us anything about the relative merits of two programs where one is always "slightly fasterthan the other howeverasymptotic analysis has proved useful to computer scientists who must determine if particular algorithm is worth considering for implementation the critical resource for program is most often its running time howeveryou cannot pay attention to running time alone you must also be concerned with other factors such as the space required to run the program (both main memory and disk spacetypically you will analyze the time required for an algorithm (or the instantiation of an algorithm in the form of program)and the space required for data structure many factors affect the running time of program some relate to the environment in which the program is compiled and run such factors include the speed of the computer' cpubusand peripheral hardware competition with other users for the computer' resources can make program slow to crawl the programming language and the quality of code generated by particular compiler can have significant effect the "coding efficiencyof the programmer who converts the algorithm to program can have tremendous impact as well if you need to get program working within time and space constraints on particular computerall of these factors can be relevant yetnone of these factors address the differences between two algorithms or data structures to be fairprograms derived from two algorithms for solving the same problem should both be
20,119
compiled with the same compiler and run on the same computer under the same conditions as much as possiblethe same amount of care should be taken in the programming effort devoted to each program to make the implementations "equally efficient in this senseall of the factors mentioned above should cancel out of the comparison because they apply to both algorithms equally if you truly wish to understand the running time of an algorithmthere are other factors that are more appropriate to consider than machine speedprogramming languagecompilerand so forth ideally we would measure the running time of the algorithm under standard benchmark conditions howeverwe have no way to calculate the running time reliably other than to run an implementation of the algorithm on some computer the only alternative is to use some other measure as surrogate for running time of primary consideration when estimating an algorithm' performance is the number of basic operations required by the algorithm to process an input of certain size the terms "basic operationsand "sizeare both rather vague and depend on the algorithm being analyzed size is often the number of inputs processed for examplewhen comparing sorting algorithmsthe size of the problem is typically measured by the number of records to be sorted basic operation must have the property that its time to complete does not depend on the particular values of its operands adding or comparing two integer variables are examples of basic operations in most programming languages summing the contents of an array containing integers is notbecause the cost depends on the value of ( the size of the inputexample consider simple algorithm to solve the problem of finding the largest value in an array of integers the algorithm looks at each integer in turnsaving the position of the largest value seen so far this algorithm is called the largest-value sequential search and is illustrated by the following function/return position of largest value in "astatic int largest(int[aint currlarge /holds largest element position for (int = < lengthi++/for each element if ( [currlargea[ ]/if [iis larger currlarge /remember its position return currlarge/return largest position herethe size of the problem is nthe number of integers stored in the basic operation is to compare an integer' value to that of the largest value
20,120
chap algorithm analysis seen so far it is reasonable to assume that it takes fixed amount of time to do one such comparisonregardless of the value of the two integers or their positions in the array because the most important factor affecting running time is normally size of the inputfor given input size we often express the time to run the algorithm as function of nwritten as (nwe will always assume (nis non-negative value let us call the amount of time required to compare two integers in function largest we do not care right now what the precise value of might be nor are we concerned with the time required to increment variable because this must be done for each value in the arrayor the time for the actual assignment when larger value is foundor the little bit of extra time taken to initialize currlarge we just want reasonable approximation for the time taken to execute the algorithm the total time to run largest is therefore approximately cnbecause we must make comparisonswith each comparison costing time we say that function largest (and the largest-value sequential search algorithm in generalhas running time expressed by the equation (ncn this equation describes the growth rate for the running time of the largestvalue sequential search algorithm example the running time of statement that assigns the first value of an integer array to variable is simply the time required to copy the value of the first array value we can assume this assignment takes constant amount of time regardless of the value let us call the amount of time necessary to copy an integer no matter how large the array on typical computer (given reasonable conditions for memory and array size)the time to copy the value from the first position of the array is always thusthe equation for this algorithm is simply (nc indicating that the size of the input has no effect on the running time this is called constant running time
20,121
example consider the following codesum for ( = <=ni++for ( = <=nj++sum++what is the running time for this code fragmentclearly it takes longer to run when is larger the basic operation in this example is the increment operation for variable sum we can assume that incrementing takes constant timecall this time (we can ignore the time required to initialize sumand to increment the loop counters and in practicethese costs can safely be bundled into time the total number of increment operations is thuswe say that the running time is (nc the growth rate for an algorithm is the rate at which the cost of the algorithm grows as the size of its input grows figure shows graph for six equationseach meant to describe the running time for particular program or algorithm variety of growth rates representative of typical algorithms are shown the two equations labeled and are graphed by straight lines growth rate of cn (for any positive constantis often referred to as linear growth rate or running time this means that as the value of growsthe running time of the algorithm grows in the same proportion doubling the value of roughly doubles the running time an algorithm whose running-time equation has highest-order term containing factor of is said to have quadratic growth rate in figure the line labeled represents quadratic growth rate the line labeled represents an exponential growth rate this name comes from the fact that appears in the exponent the line labeled nis also growing exponentially as you can see from figure the difference between an algorithm whose running time has cost ( and another with cost ( becomes tremendous as grows for the algorithm with running time ( is already much slower this is despite the fact that has greater constant factor than comparing the two curves marked and shows that changing the constant factor for one of the equations only shifts the point at which the two curves cross for the algorithm with cost ( is slower than the algorithm with cost ( this graph also shows that the equation ( log grows somewhat more quickly than both ( and ( nbut not nearly so quickly as the equation ( for constants ab na grows faster than either logb or log nb finallyalgorithms with cost ( or (nnare prohibitively expensive for even modest values of note that for constants ab > an grows faster than nb
20,122
chap algorithm analysis log log input size figure two views of graph illustrating the growth rates for six equations the bottom view shows in detail the lower-left portion of the top view the horizontal axis represents input size the vertical axis can represent timespaceor any other measure of cost
20,123
sec bestworstand average cases log log log log figure costs for growth rates representative of most computer algorithms we can get some further insight into relative growth rates for various algorithms from figure most of the growth rates that appear in typical algorithms are shownalong with some representative input sizes once againwe see that the growth rate has tremendous effect on the resources consumed by an algorithm bestworstand average cases consider the problem of finding the factorial of for this problemthere is only one input of given "size(that isthere is only single instance of size for each value of nnow consider our largest-value sequential search algorithm of example which always examines every array value this algorithm works on many inputs of given size that isthere are many possible arrays of any given size howeverno matter what array the algorithm looks atits cost will always be the same in that it always looks at every element in the array one time for some algorithmsdifferent inputs of given size require different amounts of time for exampleconsider the problem of searching an array containing integers to find the one with particular value (assume that appears exactly once in the arraythe sequential search algorithm begins at the first position in the array and looks at each value in turn until is found once is foundthe algorithm stops this is different from the largest-value sequential search algorithm of example which always examines every array value there is wide range of possible running times for the sequential search algorithm the first integer in the array could have value kand so only one integer is examined in this case the running time is short this is the best case for this algorithmbecause it is not possible for sequential search to look at less than one value alternativelyif the last position in the array contains kthen the running time is relatively longbecause the algorithm must examine values this is the worst case for this algorithmbecause sequential search never looks at more than
20,124
chap algorithm analysis values if we implement sequential search as program and run it many times on many different arrays of size nor search for many different values of within the same arraywe expect the algorithm on average to go halfway through the array before finding the value we seek on averagethe algorithm examines about / values we call this the average case for this algorithm when analyzing an algorithmshould we study the bestworstor average casenormally we are not interested in the best casebecause this might happen only rarely and generally is too optimistic for fair characterization of the algorithm' running time in other wordsanalysis based on the best case is not likely to be representative of the behavior of the algorithm howeverthere are rare instances where best-case analysis is useful -in particularwhen the best case has high probability of occurring in you will see some examples where taking advantage of the best-case running time for one sorting algorithm makes second more efficient how about the worst casethe advantage to analyzing the worst case is that you know for certain that the algorithm must perform at least that well this is especially important for real-time applicationssuch as for the computers that monitor an air traffic control system hereit would not be acceptable to use an algorithm that can handle airplanes quickly enough most of the timebut which fails to perform quickly enough when all airplanes are coming from the same direction for other applications -particularly when we wish to aggregate the cost of running the program many times on many different inputs -worst-case analysis might not be representative measure of the algorithm' performance often we prefer to know the average-case running time this means that we would like to know the typical behavior of the algorithm on inputs of size unfortunatelyaverage-case analysis is not always possible average-case analysis first requires that we understand how the actual inputs to the program (and their costsare distributed with respect to the set of all possible inputs to the program for exampleit was stated previously that the sequential search algorithm on average examines half of the array values this is only true if the element with value is equally likely to appear in any position in the array if this assumption is not correctthen the algorithm does not necessarily examine half of the array values in the average case see section for further discussion regarding the effects of data distribution on the sequential search algorithm the characteristics of data distribution have significant effect on many search algorithmssuch as those based on hashing (section and search trees ( see section incorrect assumptions about data distribution can have dis
20,125
astrous consequences on program' space or time performance unusual data distributions can also be used to advantageas shown in section in summaryfor real-time applications we are likely to prefer worst-case analysis of an algorithm otherwisewe often desire an average-case analysis if we know enough about the distribution of our input to compute the average case if notthen we must resort to worst-case analysis faster computeror faster algorithmimagine that you have problem to solveand you know of an algorithm whose running time is proportional to unfortunatelythe resulting program takes ten times too long to run if you replace your current computer with new one that is ten times fasterwill the algorithm become acceptableif the problem size remains the samethen perhaps the faster computer will allow you to get your work done quickly enough even with an algorithm having high growth rate but funny thing happens to most people who get faster computer they don' run the same problem faster they run bigger problemsay that on your old computer you were content to sort , records because that could be done by the computer during your lunch break on your new computer you might hope to sort , records in the same time you won' be back from lunch any soonerso you are better off solving larger problem and because the new machine is ten times fasteryou would like to sort ten times as many records if your algorithm' growth rate is linear ( if the equation that describes the running time on input size is (ncn for some constant )then , records on the new machine will be sorted in the same time as , records on the old machine if the algorithm' growth rate is greater than cnsuch as then you will not be able to do problem ten times the size in the same amount of time on machine that is ten times faster how much larger problem can be solved in given amount of time by faster computerassume that the new machine is ten times faster than the old say that the old machine could solve problem of size in an hour what is the largest problem that the new machine can solve in one hourfigure shows how large problem can be solved on the two machines for the five running-time functions from figure this table illustrates many important points the first two equations are both linearonly the value of the constant factor has changed in both casesthe machine that is ten times faster gives an increase in problem size by factor of ten in other wordswhile the value of the constant does affect the absolute size of the problem that can be solved in fixed amount of timeit does not affect the improvement in
20,126
chap algorithm analysis (nn change / log nn -figure the increase in problem size that can be run in fixed period of time on computer that is ten times faster the first column lists the right-hand sides for each of the five growth rate equations of figure for the purpose of this examplearbitrarily assume that the old machine can run , basic operations in one hour the second column shows the maximum value for that can be run in , basic operations on the old machine the third column shows the value for the new maximum size for the problem that can be run in the same time on the new machine that is ten times faster variable is the greatest size for the problem that can run in , basic operations the fourth column shows how the size of changed to become on the new machine the fifth column shows the increase in the problem size as the ratio of to problem size (as proportion to the original sizegained by faster computer this relationship holds true regardless of the algorithm' growth rateconstant factors never affect the relative improvement gained by faster computer an algorithm with time equation ( does not receive nearly as great an improvement from the faster machine as an algorithm with linear growth rate instead of an improvement by factor of tenthe improvement is only the square root of that thusthe algorithm with higher growth rate not only solves smaller problem in given time in the first placeit also receives less of speedup from faster computer as computers get ever fasterthe disparity in problem sizes becomes ever greater the algorithm with growth rate ( log improves by greater amount than the one with quadratic growth ratebut not by as great an amount as the algorithms with linear growth rates note that something special happens in the case of the algorithm whose running time grows exponentially in figure the curve for the algorithm whose time is proportional to goes up very quickly in figure the increase in problem size on the machine ten times as fast is shown to be about (to be preciseit is log the increase in problem size for an algorithm with exponential growth rate is by constant additionnot by multiplicative factor because the old value of was the new problem size is if next year you buy another
20,127
computer ten times faster yetthen the new computer ( times faster than the original computerwill only run problem of size if you had second program whose growth rate is and for which the original computer could run problem of size in an hourthan machine ten times faster can run problem only of size in an hourthusan exponential growth rate is radically different than the other growth rates shown in figure the significance of this difference is explored in instead of buying faster computerconsider what happens if you replace an algorithm whose running time is proportional to with new algorithm whose running time is proportional to log in the graph of figure fixed amount of time would appear as horizontal line if the line for the amount of time available to solve your problem is above the point at which the curves for the two growth rates in question meetthen the algorithm whose running time grows less quickly is faster an algorithm with running time (nn requires time steps for an input of size an algorithm with running time (nn log requires time steps for an input of size which is an improvement of much more than factor of ten when compared to the algorithm with running time (nn because log whenever if the typical problem size is larger than for this examplethen you would be much better off changing algorithms instead of buying computer ten times faster furthermorewhen you do buy faster computeran algorithm with slower growth rate provides greater benefit in terms of larger problem size that can run in certain time on the new computer asymptotic analysis despite the larger constant for the curve labeled in figure the curve labeled crosses it at the relatively small value of what if we double the value of the constant in front of the linear equationas shown in the graphthe curve labeled is surpassed by the curve labeled once the additional factor of two for the linear growth rate does not much matterit only doubles the -coordinate for the intersection point in generalchanges to constant factor in either equation only shift where the two curves crossnot whether the two curves cross when you buy faster computer or faster compilerthe new problem size that can be run in given amount of time for given growth rate is larger by the same factorregardless of the constant on the running-time equation the time curves for two algorithms with different growth rates still crossregardless of their running-time equation constants for these reasonswe usually ignore the constants
20,128
chap algorithm analysis when we want an estimate of the running time or other resource requirements of an algorithm this simplifies the analysis and keeps us thinking about the most important aspectthe growth rate this is called asymptotic algorithm analysis to be preciseasymptotic analysis refers to the study of an algorithm as the input size "gets bigor reaches limit (in the calculus sensehoweverit has proved to be so useful to ignore all constant factors that asymptotic analysis is used for most algorithm comparisons it is not always reasonable to ignore the constants when comparing algorithms meant to run on small values of nthe constant can have large effect for exampleif the problem is to sort collection of exactly five recordsthen an algorithm designed for sorting thousands of records is probably not appropriateeven if its asymptotic analysis indicates good performance there are rare cases where the constants for two algorithms under comparison can differ by factor of or moremaking the one with lower growth rate impractical for most purposes due to its large constant asymptotic analysis is form of "back of the envelopeestimation for algorithm resource consumption it provides simplified model of the running time or other resource needs of an algorithm this simplification usually helps you understand the behavior of your algorithms just be aware of the limitations to asymptotic analysis in the rare situation where the constant is important upper bounds several terms are used to describe the running-time equation for an algorithm these terms -and their associated symbols -indicate precisely what aspect of the algorithm' behavior is being described one is the upper bound for the growth of the algorithm' running time it indicates the upper or highest growth rate that the algorithm can have to make any statement about the upper bound of an algorithmwe must be making it about some class of inputs of size we measure this upper bound nearly always on the best-caseaverage-caseor worst-case inputs thuswe cannot say"this algorithm has an upper bound to its growth rate of we must say something like"this algorithm has an upper bound to its growth rate of in the average case because the phrase "has an upper bound to its growth rate of ( )is long and often used when discussing algorithmswe adopt special notationcalled big-oh notation if the upper bound for an algorithm' growth rate (forsaythe worst caseis ( )then we would write that this algorithm is "in the set ( ( ))in the worst case(or just "in ( ( ))in the worst case"for exampleif grows as
20,129
fast as ( (the running time of our algorithmfor the worst-case inputwe would say the algorithm is "in ( in the worst case the following is precise definition for an upper bound (nrepresents the true running time of the algorithm (nis some expression for the upper bound for (na non-negatively valued functiont(nis in set ( ( )if there exist two positive constants and such that ( <cf (nfor all constant is the smallest value of for which the claim of an upper bound holds true usually is smallsuch as but does not need to be you must also be able to pick some constant cbut it is irrelevant what the value for actually is in other wordsthe definition says that for all inputs of the type in question (such as the worst case for all inputs of size nthat are large enough ( )the algorithm always executes in less than cf (nsteps for some constant example consider the sequential search algorithm for finding specified value in an array of integers if visiting and examining one value in the array requires cs steps where cs is positive numberand if the value we search for has equal probability of appearing in any position in the arraythen in the average case (ncs / for all values of cs / <cs thereforeby the definitiont(nis in (nfor and cs example for particular algorithmt(nc in the average case where and are positive numbers thenc < sot( <cn for and thereforet(nis in ( by the definition example assigning the value from the first position of an array to variable takes constant time regardless of the size of the array thust(nc (for the bestworstand average caseswe could say in this case that (nis in (choweverit is traditional to say that an algorithm whose running time has constant upper bound is in ( just knowing that something is in ( ( )says only how bad things can get perhaps things are not nearly so bad because we know sequential search is in (nin the worst caseit is also true to say that sequential search is in ( but
20,130
chap algorithm analysis sequential search is practical for large nin way that is not true for some other algorithms in ( we always seek to define the running time of an algorithm with the tightest (lowestpossible upper bound thuswe prefer to say that sequential search is in (nthis also explains why the phrase "is in ( ( ))or the notation ( ( ))is used instead of "is ( ( ))or " ( ( )there is no strict equality to the use of big-oh notation (nis in ( )but ( is not in (nlower bounds big-oh notation describes an upper bound in other wordsbig-oh notation states claim about the greatest amount of some resource (usually timethat is required by an algorithm for some class of inputs of size (typically the worst such inputthe average of all possible inputsor the best such inputsimilar notation is used to describe the least amount of resource that an algorithm needs for some class of input like big-oh notationthis is measure of the algorithm' growth rate like big-oh notationit works for any resourcebut we most often measure the least amount of time required and againlike big-oh notationwe are measuring the resource required for some particular class of inputsthe worst-average-or best-case input of size the lower bound for an algorithm (or problemas explained lateris denoted by the symbol ohmpronounced "big-omegaor just "omega the following definition for ohm is symmetric with the definition of big-oh for (na non-negatively valued functiont(nis in set ohm( ( )if there exist two positive constants and such that ( >cg(nfor all an alternate (non-equivalentdefinition for ohm is (nis in the set ohm( ( )if there exists positive constant such that ( >cg(nfor an infinite number of values for this definition says that for an "interestingnumber of casesthe algorithm takes at least cg(ntime note that this definition is not symmetric with the definition of big-oh for (nto be lower boundthis definition does not require that ( >cg(nfor all values of greater than some constant it only requires that this happen often enoughin particular that it happen for an infinite number of values for motivation for this alternate definition can be found in the following example assume particular algorithm has the following behaviorn for all odd > (nn / for all even > for all even > sot( >cn for an infinite number from this definitionn / > of values of ( for all even nfor / thereforet(nis in ohm( by the definition
20,131
sec asymptotic analysis example assume (nc for and thenc > for all sot( >cn for and thereforet(nis in ohm( by the definition it is also true that the equation of example is in ohm(nhoweveras with big-oh notationwe wish to get the "tightest(for ohm notationthe largestbound possible thuswe prefer to say that this running time is in ohm( recall the sequential search algorithm to find value within an array of integers in the average and worst cases this algorithm is in ohm( )because in both the average and worst cases we must examine at least cn values (where is / in the average case and in the worst caseth notation the definitions for big-oh and ohm give us ways to describe the upper bound for an algorithm (if we can find an equation for the maximum cost of particular class of inputs of size nand the lower bound for an algorithm (if we can find an equation for the minimum cost for particular class of inputs of size nwhen the upper and lower bounds are the same within constant factorwe indicate this by using th (big-thetanotation an algorithm is said to be th( ( )if it is in ( ( )and it is in ohm( ( )note that we drop the word "infor th notationbecause there is strict equality for two equations with the same th in other wordsif (nis th( ( ))then (nis th( ( )because the sequential search algorithm is both in (nand in ohm(nin the average casewe say it is th(nin the average case given an algebraic equation describing the time requirement for an algorithmthe upper and lower bounds always meet that is because in some sense we have perfect analysis for the algorithmembodied by the running-time equation for for this equation for ( )it is true that all inputs of size take at least cn time but an infinite number of inputs of size take cn timeso we would like to say that the algorithm is in ohm( unfortunatelyusing our first definition will yield lower bound of ohm(nbecause it is not possible to pick constants and such that ( >cn for all the alternative definition does result in lower bound of ohm( for this algorithmwhich seems to fit common sense more closely fortunatelyfew real algorithms or computer programs display the pathological behavior of this example our first definition for ohm generally yields the expected result as you can see from this discussionasymptotic bounds notation is not law of nature it is merely powerful modeling tool used to describe the behavior of algorithms
20,132
chap algorithm analysis many algorithms (or their instantiations as programs)it is easy to come up with the equation that defines their runtime behavior most algorithms presented in this book are well understood and we can almost always give th analysis for them however discusses whole class of algorithms for which we have no th analysisjust some unsatisfying big-oh and ohm analyses exercise presents shortsimple program fragment for which nobody currently knows the true upper or lower bounds while some textbooks and programmers will casually say that an algorithm is "order ofor "big-ohof some cost functionit is generally better to use th notation rather than big-oh notation whenever we have sufficient knowledge about an algorithm to be sure that the upper and lower bounds indeed match throughout this bookth notation will be used in preference to big-oh notation whenever our state of knowledge makes that possible limitations on our ability to analyze certain algorithms may require use of big-oh or ohm notations in rare occasions when the discussion is explicitly about the upper or lower bound of problem or algorithmthe corresponding notation will be used in preference to th notation simplifying rules once you determine the running-time equation for an algorithmit really is simple matter to derive the big-ohohmand th expressions from the equation you do not need to resort to the formal definitions of asymptotic analysis insteadyou can use the following rules to determine the simplest form if (nis in ( ( )and (nis in ( ( ))then (nis in ( ( ) if (nis in (kg( )for any constant then (nis in ( ( ) if (nis in ( ( )and (nis in ( ( ))then (nf (nis in (max( ( ) ( )) if (nis in ( ( )and (nis in ( ( ))then ( ) (nis in ( ( ) ( )the first rule says that if some function (nis an upper bound for your cost functionthen any upper bound for (nis also an upper bound for your cost function similar property holds true for ohm notationif (nis lower bound for your cost functionthen any lower bound for (nis also lower bound for your cost function likewise for th notation the significance of rule ( is that you can ignore any multiplicative constants in your equations when using big-oh notation this rule also holds true for ohm and th notations
20,133
sec asymptotic analysis rule ( says that given two parts of program run in sequence (whether two statements or two sections of code)you need consider only the more expensive part this rule applies to ohm and th notations as wellfor bothyou need consider only the more expensive part rule ( is used to analyze simple loops in programs if some action is repeated some number of timesand each repetition has the same costthen the total cost is the cost of the action multiplied by the number of times that the action takes place this rule applies to ohm and th notations as well taking the first three rules collectivelyyou can ignore all constants and all lower-order terms to determine the asymptotic growth rate for any cost function the advantages and dangers of ignoring constants were discussed near the beginning of this section ignoring lower-order terms is reasonable when performing an asymptotic analysis the higher-order terms soon swamp the lower-order terms in their contribution to the total cost as becomes larger thusif ( then (nis in ( the term contributes relatively little to the total cost throughout the rest of this bookthese simplifying rules are used when discussing the cost for program or algorithm classifying functions given functions (nand (nwhose growth rates are expressed as algebraic equationswe might like to determine if one grows faster than the other the best way to do this is to take the limit of the two functions as grows towards infinityf (nng(nlim if the limit goes to then (nis in ohm( ( )because (ngrows faster if the limit goes to zerothen (nis in ( ( )because (ngrows faster if the limit goes to some constant other than zerothen (nth( ( )because both grow at the same rate example if ( log and (nn is (nin ( ( ))ohm( ( ))or th( ( ))because log log we easily see that log lim
20,134
chap algorithm analysis because grows faster than log thusn is in ohm( log calculating the running time for program this section presents the analysis for several simple code fragments example we begin with an analysis of simple assignment statement to an integer variable bbecause the assignment statement takes constant timeit is th( example consider simple for loop sum for ( = <=ni++sum +nthe first line is th( the for loop is repeated times the third line takes constant time soby simplifying rule ( of section the total cost for executing the two lines making up the for loop is th(nby rule ( )the cost of the entire code fragment is also th(nexample we now analyze code fragment with several for loopssome of which are nested sum for ( = <=nj++for ( = <=ji++sum++for ( = <nk++ [kk/first for loop /is double loop /second for loop this code fragment has three separate statementsthe first assignment statement and the two for loops again the assignment statement takes constant timecall it the second for loop is just like the one in example and takes th(ntime the first for loop is double loop and requires special technique we work from the inside of the loop outward the expression sum+requires constant timecall it because the inner for loop is executed timesby simplifying rule ( it has cost the outer for loop is executed times
20,135
but each time the cost of the inner loop is different because it costs with changing each time you should see that for the first execution of the outer loopi is for the second execution of the outer loopi is each time through the outer loopi becomes one greateruntil the last time through the loop when thusthe total cost of the loop is times the sum of the integers through from equation we know that = in( which is th( by simplifying rule ( )th( is simply th( example compare the asymptotic analysis for the following two code fragmentssum for ( = <=ni++for ( = <=nj++sum ++/first double loop /do times sum for ( = <=ni++for ( = <=ij++sum ++/second double loop /do times in the first double loopthe inner for loop always executes times because the outer loop executes timesit should be obvious that the statement sum +is executed precisely times the second loop is similar to the one analyzed in the previous examplewith cost nj= this is approximately thusboth double loops cost th( )though the second requires about half the time of the first example not all doubly nested for loops are th( the following pair of nested loops illustrates this fact
20,136
chap algorithm analysis sum for ( = <=nk*= for ( = <=nj++sum ++/do log times /do times sum for ( = <=nk*= for ( = <=kj++sum ++/do log times /do times when analyzing these two code fragmentswe will assume that is power of two the first code fragment has its outer for loop executed log times because on each iteration is multiplied by two until it reaches because the inner loop always executes plog nn timesthe total cost for the first code fragment can be expressed as = note that variable substitution takes place here to create the summationwith from equation the solution for this summation is th( log nin the second code fragmentthe outer loop is also executed log times the inner loop cost kwhich doubles each time the summation can be expressed phas log as = where is assumed to be power of two and again from equation we know that this summation is simply th(nwhat about other control statementswhile loops are analyzed in manner similar to for loops the cost of an if statement in the worst case is the greater of the costs for the then and else clauses this is also true for the average caseassuming that the size of does not affect the probability of executing one of the clauses (which is usuallybut not necessarilytruefor switch statementsthe worst-case cost is that of the most expensive branch for subroutine callssimply add the cost of executing the subroutine there are rare situations in which the probability for executing the various branches of an if or switch statement are functions of the input size for examplefor input of size nthe then clause of an if statement might be executed with probability / an example would be an if statement that executes the then clause only for the smallest of values to perform an average-case analysis for such programswe cannot simply count the cost of the if statement as being the cost of the more expensive branch in such situationsthe technique of amortized analysis (see section can come to the rescue determining the execution time of recursive subroutine can be difficult the running time for recursive subroutine is typically best expressed by recurrence relation for examplethe recursive factorial function fact of section calls itself with value one less than its input value the result of this recursive call is
20,137
then multiplied by the input valuewhich takes constant time thusthe cost of the factorial functionif we wish to measure cost in terms of the number of multiplication operationsis one more than the number of multiplications made by the recursive call on the smaller input because the base case does no multiplicationsits cost is zero thusthe running time for this function can be expressed as (nt( for ( we know from examples and that the closed-form solution for this recurrence relation is th(nthe final example of algorithm analysis for this section will compare two algorithms for performing search in an array earlierwe determined that the running time for sequential search on an array where the search value is equally likely to appear in any location is th(nin both the average and worst cases we would like to compare this running time to that required to perform binary search on an array whose values are stored in order from lowest to highest binary search begins by examining the value in the middle position of the arraycall this position mid and the corresponding value kmid if kmid kthen processing can stop immediately this is unlikely to be the casehowever fortunatelyknowing the middle value provides useful information that can help guide the search process in particularif kmid kthen you know that the value cannot appear in the array at any position greater than mid thusyou can eliminate future search in the upper half of the array converselyif kmid kthen you know that you can ignore all positions in the array less than mid either wayhalf of the positions are eliminated from further consideration binary search next looks at the middle position in that part of the array where value may exist the value at this position again allows us to eliminate half of the remaining positions from consideration this process repeats until either the desired value is foundor there are no positions remaining in the array that might contain the value figure illustrates the binary search method here is an implementation for binary search/return the position of an element in sorted array " /with value "kif "kis not in " "return length static int binary(int[aint kint - int length/ and are beyond array bounds while ( + ! /stop when and meet int ( + )/ /check middle of remaining subarray if ( [ ] /in left half if ( = [ ]return /found it if ( [ ] /in right half return length/search value not in
20,138
chap algorithm analysis position key figure an illustration of binary search on sorted array of positions consider search for the position with value binary search first checks the value at position because kthe desired value cannot appear in any position below in the array nextbinary search checks the value at position because kthe desired value (if it existsmust be between positions and position is checked next againits value is too great the final search is at position which contains the desired value thusfunction binary returns position alternativelyif were then the same series of record accesses would be made after checking position binary would return value of nindicating that the search is unsuccessful to find the cost of this algorithm in the worst casewe can model the running time as recurrence and then find the closed-form solution each recursive call to binary cuts the size of the array approximately in halfso we can model the worst-case cost as followsassuming for simplicity that is power of two (nt( / for ( if we expand the recurrencewe find that we can do so only log times before we reach the base caseand each expansion adds one to the cost thusthe closedform solution for the recurrence is (nlog function binary is designed to find the (singleoccurrence of and return its position special value is returned if does not appear in the array this algorithm can be modified to implement variations such as returning the position of the first occurrence of in the array if multiple occurrences are allowedand returning the position of the greatest value less than when is not in the array comparing sequential search to binary searchwe see that as growsthe th(nrunning time for sequential search in the average and worst cases quickly becomes much greater than the th(log nrunning time for binary search taken in isolationbinary search appears to be much more efficient than sequential search this is despite the fact that the constant factor for binary search is greater than that for sequential searchbecause the calculation for the next search position in binary search is more expensive than just incrementing the current positionas sequential search does note however that the running time for sequential search will be roughly the same regardless of whether or not the array values are stored in order in contrast
20,139
binary search requires that the array values be ordered from lowest to highest depending on the context in which binary search is to be usedthis requirement for sorted array could be detrimental to the running time of complete programbecause maintaining the values in sorted order requires to greater cost when inserting new elements into the array this is an example of tradeoff between the advantage of binary search during search and the disadvantage related to maintaining sorted array only in the context of the complete problem to be solved can we know whether the advantage outweighs the disadvantage analyzing problems you most often use the techniques of "algorithmanalysis to analyze an algorithmor the instantiation of an algorithm as program you can also use these same techniques to analyze the cost of problem it should make sense to you to say that the upper bound for problem cannot be worse than the upper bound for the best algorithm that we know for that problem but what does it mean to give lower bound for problemconsider graph of cost over all inputs of given size for some algorithm for given problem define to be the collection of all algorithms that solve the problem (theoreticallythere an infinite number of such algorithmsnowconsider the collection of all the graphs for all of the (infinitely manyalgorithms in the worst case lower bound is the least of all the highest points on all the graphs it is much easier to show that an algorithm (or programis in ohm( ( )than it is to show that problem is in ohm( ( )for problem to be in ohm( ( )means that every algorithm that solves the problem is in ohm( ( ))even algorithms that we have not thought ofso far all of our examples of algorithm analysis give "obviousresultswith big-oh always matching ohm to understand how big-ohohmand th notations are properly used to describe our understanding of problem or an algorithmit is best to consider an example where you do not already know lot about the problem let us look ahead to analyzing the problem of sorting to see how this process works what is the least possible cost for any sorting algorithm in the worst casethe algorithm must at least look at every element in the inputjust to determine that the input is truly sorted it is also possible that each of the values must be moved to another location in the sorted output thusany sorting algorithm must take at least cn time for many problemsthis observation that each of the inputs must be looked at leads to an easy ohm(nlower bound in your previous study of computer scienceyou have probably seen an example of sorting algorithm whose running time is in ( in the worst case the simple
20,140
chap algorithm analysis bubble sort and insertion sort algorithms typically given as examples in first year programming course have worst case running times in ( thusthe problem of sorting can be said to have an upper bound in ( how do we close the gap between ohm(nand ( )can there be better sorting algorithmif you can think of no algorithm whose worst-case growth rate is better than ( )and if you have discovered no analysis technique to show that the least cost for the problem of sorting in the worst case is greater than ohm( )then you cannot know for sure whether or not there is better algorithm presents sorting algorithms whose running time is in ( log nfor the worst case this greatly narrows the gap with this new knowledgewe now have lower bound in ohm(nand an upper bound in ( log nshould we search for faster algorithmmany have triedwithout success fortunately (or perhaps unfortunately?) also includes proof that any sorting algorithm must have running time in ohm( log nin the worst case this proof is one of the most important results in the field of algorithm analysisand it means that no sorting algorithm can possibly run faster than cn log for the worst-case input of size thuswe can conclude that the problem of sorting is th( log nin the worst casebecause the upper and lower bounds have met knowing the lower bound for problem does not give you good algorithm but it does help you to know when to stop looking if the lower bound for the problem matches the upper bound for the algorithm (within constant factor)then we know that we can find an algorithm that is better only by constant factor common misunderstandings asymptotic analysis is one of the most intellectually difficult topics that undergraduate computer science majors are confronted with most people find growth rates and asymptotic analysis confusing and so develop misconceptions about either the concepts or the terminology it helps to know what the standard points of confusion arein hopes of avoiding them one problem with differentiating the concepts of upper and lower bounds is thatfor most algorithms that you will encounterit is easy to recognize the true growth rate for that algorithm given complete knowledge about cost functionthe upper and lower bound for that cost function are always the same thusthe distinction between an upper and lower bound is only worthwhile when you have incomplete knowledge about the thing being measured if this distinction is still not while it is fortunate to know the truthit is unfortunate that sorting is th( log nrather than th( )
20,141
clearreread section we use th-notation to indicate that there is no meaningful difference between what we know about the growth rates of the upper and lower bound (which is usually the case for simple algorithmsit is common mistake to confuse the concepts of upper bound or lower bound on the one handand worst case or best case on the other the bestworstor average cases each give us concrete instance that we can apply to an algorithm description to get cost measure the upper and lower bounds describe our understanding of the growth rate for that cost measure so to define the growth rate for an algorithm or problemwe need to determine what we are measuring (the bestworstor average caseand also our description for what we know about the growth rate of that cost measure (big-ohohmor ththe upper bound for an algorithm is not the same as the worst case for that algorithm for given input of size what is being bounded is not the actual cost (which you can determine for given value of )but rather the growth rate for the cost there cannot be growth rate for single pointsuch as particular value of the growth rate applies to the change in cost as change in input size occurs likewisethe lower bound is not the same as the best case for given size another common misconception is thinking that the best case for an algorithm occurs when the input size is as small as possibleor that the worst case occurs when the input size is as large as possible what is correct is that bestand worsecase instances exist for each possible size of input that isfor all inputs of given sizesay ione (or moreof the inputs of size is the best and one (or moreof the inputs of size is the worst often (but not always!)we can characterize the best input case for an arbitrary sizeand we can characterize the worst input case for an arbitrary size ideallywe can determine the growth rate for the bestworstand average cases as the input size grows example what is the growth rate of the best case for sequential searchfor any array of size nthe best case occurs when the value we are looking for appears in the first position of the array this is true regardless of the size of the array thusthe best case (for arbitrary size noccurs when the desired value is in the first of positionsand its cost is it is not correct to say that the best case occurs when example imagine drawing graph to show the cost of finding the maximum value among valuesas grows that isthe axis would be nand the value would be the cost of coursethis is diagonal line
20,142
chap algorithm analysis going up to the rightas increases (you might want to sketch this graph for yourself before reading furthernowimagine the graph showing the cost for each instance of the problem of finding the maximum value among (say elements in an array the first position along the axis of the graph might correspond to having the maximum element in the first position of the array the second position along the axis of the graph might correspond to having the maximum element in the second position of the arrayand so on of coursethe cost is always thereforethe graph would be horizontal line with value you should sketch this graph for yourself nowlet' switch to the problem of doing sequential search for given value in an array think about the graph showing all the problem instances of size the first problem instance might be when the value we search for is in the first position of the array this has cost the second problem instance might be when the value we search for is in the second position of the array this has cost and so on if we arrange the problem instances of size from least expensive on the left to most expensive on the rightwe see that the graph forms diagonal line from lower left (with value to upper right (with value sketch this graph for yourself finallylets consider the cost for performing sequential search as the size of the array gets bigger what will this graph look likeunfortunatelythere' not one simple answeras there was for finding the maximum value the shape of this graph depends on whether we are considering the best case cost (that would be horizontal line with value )the worst case cost (that would be diagonal line with value at position along the axis)or the average cost (that would be diagonal line with value / at position along the axisthis is why we must always say that function (nis in ( ( )in the bestaverageor worst caseif we leave off which class of inputs we are discussingwe cannot know which cost measure we are referring to for most algorithms multiple parameters sometimes the proper analysis for an algorithm requires multiple parameters to describe the cost to illustrate the conceptconsider an algorithm to compute the rank ordering for counts of all pixel values in picture pictures are often represented by two-dimensional arrayand pixel is one cell in the array the value of pixel is either the code value for the coloror value for the intensity of the picture at that
20,143
pixel assume that each pixel can take any integer value in the range to the problem is to find the number of pixels of each color value and then sort the color values with respect to the number of times each value appears in the picture assume that the picture is rectangle with pixels pseudocode algorithm to solve the problem follows for ( = <ci++/initialize count count[ for ( = <pi++/look at all of the pixels count[value( )]++/increment pixel value count sort(count)/sort pixel value counts in this examplecount is an array of size that stores the number of pixels for each color value function value(ireturns the color value for pixel the time for the first for loop (which initializes countis based on the number of colorsc the time for the second loop (which determines the number of pixels with each coloris th( the time for the final linethe call to sortdepends on the cost of the sorting algorithm used from the discussion of section we can assume that the sorting algorithm has cost th( log if items are sortedthus yielding th( log as the total algorithm cost is this good representation for the cost of this algorithmwhat is actually being sortedit is not the pixelsbut rather the colors what if is much smaller than then the estimate of th( log is pessimisticbecause much fewer than items are being sorted insteadwe should use as our analysis variable for steps that look at each pixeland as our analysis variable for steps that look at colors then we get th(cfor the initialization loopth( for the pixel count loopand th( log cfor the sorting operation this yields total cost of th( log cwhy can we not simply use the value of for input size and say that the cost of the algorithm is th( log )becausec is typically much less than for examplea picture might have pixels and range of possible colors sop is one millionwhich is much larger than log butif is smalleror larger (even if it is still less than )then log can become the larger quantity thusneither variable should be ignored space bounds besides timespace is the other computing resource that is commonly of concern to programmers just as computers have become much faster over the yearsthey have also received greater allotments of memory even sothe amount of available disk space or main memory can be significant constraints for algorithm designers
20,144
chap algorithm analysis the analysis techniques used to measure space requirements are similar to those used to measure time requirements howeverwhile time requirements are normally measured for an algorithm that manipulates particular data structurespace requirements are normally determined for the data structure itself the concepts of asymptotic analysis for growth rates on input size apply completely to measuring space requirements example what are the space requirements for an array of integersif each integer requires bytesthen the array requires cn byteswhich is th(nexample imagine that we want to keep track of friendships between people we can do this with an array of size each row of the array represents the friends of an individualwith the columns indicating who has that individual as friend for exampleif person is friend of person ithen we place mark in column of row in the array likewisewe should also place mark in column of row if we assume that friendship works both ways for peoplethe total size of the array is th( data structure' primary purpose is to store data in way that allows efficient access to those data to provide efficient accessit may be necessary to store additional information about where the data are within the data structure for exampleeach node of linked list must store pointer to the next value on the list all such information stored in addition to the actual data values is referred to as overhead ideallyoverhead should be kept to minimum while allowing maximum access the need to maintain balance between these opposing goals is what makes the study of data structures so interesting one important aspect of algorithm design is referred to as the space/time tradeoff principle the space/time tradeoff principle says that one can often achieve reduction in time if one is willing to sacrifice space or vice versa many programs can be modified to reduce storage requirements by "packingor encoding information "unpackingor decoding the information requires additional time thusthe resulting program uses less space but runs slower converselymany programs can be modified to pre-store results or reorganize information to allow faster running time at the expense of greater storage requirements typicallysuch changes in time and space are both by constant factor
20,145
classic example of space/time tradeoff is the lookup table lookup table pre-stores the value of function that would otherwise be computed each time it is needed for example is the greatest value for the factorial function that can be stored in -bit int variable if you are writing program that often computes factorialsit is likely to be much more time efficient to simply pre-compute the storable values in table whenever the program needs the value of nfor < it can simply check the lookup table (if the value is too large to store as an int variable anyway compared to the time required to compute factorialsit may be well worth the small amount of additional space needed to store the lookup table lookup tables can also store approximations for an expensive function such as sine or cosine if you compute this function only for exact degrees or are willing to approximate the answer with the value for the nearest degreethen lookup table storing the computation for exact degrees can be used instead of repeatedly computing the sine function note that initially building the lookup table requires certain amount of time your application must use the lookup table often enough to make this initialization worthwhile another example of the space/time tradeoff is typical of what programmer might encounter when trying to optimize space here is simple code fragment for sorting an array of integers we assume that this is special case where there are integers whose values are permutation of the integers from to this is an example of binsortwhich is discussed in section binsort assigns each value to an array position corresponding to its value for ( = <ni++ [ [ ] [ ]this is efficient and requires th(ntime howeverit also requires two arrays of size next is code fragment that places the permutation in order but does so within the same array (thus it is an example of an "in placesortfor ( = <ni++while ( [ ! /swap element [iwith [ [ ]dsutil swap(aia[ ])function swap(aijexchanges elements and in array (see the appendixit may not be obvious that the second code fragment actually sorts the array to see that this does worknotice that each pass through the for loop will at least move the integer with value to its correct position in the arrayand that during this iterationthe value of [imust be greater than or equal to total of at most swap operations take placebecause an integer cannot be moved out
20,146
chap algorithm analysis of its correct position once it has been placed thereand each swap operation places at least one integer in its correct position thusthis code fragment has cost th(nhoweverit requires more time to run than the first code fragment on my computer the second version takes nearly twice as long to run as the firstbut it only requires half the space second principle for the relationship between program' space and time requirements applies to programs that process information stored on diskas discussed in and thereafter strangely enoughthe disk-based space/time tradeoff principle is almost the reverse of the space/time tradeoff principle for programs using main memory the disk-based space/time tradeoff principle states that the smaller you can make your disk storage requirementsthe faster your program will run this is because the time to read information from disk is enormous compared to computation timeso almost any amount of additional computation needed to unpack the data is going to be less than the disk-reading time saved by reducing the storage requirements naturally this principle does not hold true in all casesbut it is good to keep in mind when designing programs that process information stored on disk speeding up your programs in practicethere is not such big difference in running time between an algorithm whose growth rate is th(nand another whose growth rate is th( log nthere ishoweveran enormous difference in running time between algorithms with growth rates of th( log nand th( as you shall see during the course of your study of common data structures and algorithmsit is not unusual that problem whose obvious solution requires th( time also has solution that requires th( log ntime examples include sorting and searchingtwo of the most important computer problems example the following is true story few years agoone of my graduate students had big problem his thesis work involved several intricate operations on large database he was now working on the final step "dr shaffer,he said" am running this program and it seems to be taking long time after examining the algorithm we realized that its running time was th( )and that it would likely take one to two weeks to complete even if we could keep the computer running uninterrupted for that longhe was hoping to complete his thesis and graduate before then fortunatelywe realized that there was fairly easy way to convert the algorithm so that its running time was th( log nby the next day he
20,147
had modified the program it ran in only few hoursand he finished his thesis on time while not nearly so important as changing an algorithm to reduce its growth rate"code tuningcan also lead to dramatic improvements in running time code tuning is the art of hand-optimizing program to run faster or require less storage for many programscode tuning can reduce running time by factor of tenor cut the storage requirements by factor of two or more once tuned critical function in program -without changing its basic algorithm -to achieve factor of speedup to get this speeduphoweveri did make major changes in the representation of the informationconverting from symbolic coding scheme to numeric coding scheme on which was able to do direct computation here are some suggestions for ways to speed up your programs by code tuning the most important thing to realize is that most statements in program do not have much effect on the running time of that program there are normally just few key subroutinespossibly even key lines of code within the key subroutinesthat account for most of the running time there is little point to cutting in half the running time of subroutine that accounts for only of the total running time focus your attention on those parts of the program that have the most impact when tuning codeit is important to gather good timing statistics many compilers and operating systems include profilers and other special tools to help gather information on both time and space use these are invaluable when trying to make program more efficientbecause they can tell you where to invest your effort lot of code tuning is based on the principle of avoiding work rather than speeding up work common situation occurs when we can test for condition that lets us skip some work howeversuch test is never completely free care must be taken that the cost of the test does not exceed the amount of work saved while one test might be cheaper than the work potentially savedthe test must always be made and the work can be avoided only some fraction of the time example common operation in computer graphics applications is to find which among set of complex objects contains given point in space many useful data structures and algorithms have been developed to deal with variations of this problem most such implementations involve the following tuning step directly testing whether given complex object contains the point in question is relatively expensive insteadwe can screen for whether the point is contained within bounding box for the object the bounding box is simply the smallest rectangle (usually defined
20,148
chap algorithm analysis to have sides perpendicular to the and axesthat contains the object if the point is not in the bounding boxthen it cannot be in the object if the point is in the bounding boxonly then would we conduct the full comparison of the object versus the point note that if the point is outside the bounding boxwe saved time because the bounding box test is cheaper than the comparison of the full object versus the point but if the point is inside the bounding boxthen that test is redundant because we still have to compare the point against the object typically the amount of work avoided by making this test is greater than the cost of making the test on every object example section presents sorting algorithm named selection sort the chief distinguishing characteristic of this algorithm is that it requires relatively few swaps of records stored in the array being sorted howeverit sometimes performs an unnecessary swap operationspecifically when it tries to swap record with itself this work could be avoided by testing whether the two indices being swapped are the same howeverthis event has insufficient chance of occurring because the cost of the test is high enough compared to the work saved when the test is successfuladding the test typically will slow down the program rather than speed it up be careful not to use tricks that make the program unreadable most code tuning is simply cleaning up carelessly written programnot taking clear program and adding tricks in particularyou should develop an appreciation for the capabilities of modern compilers to make extremely good optimizations of expressions "optimization of expressionshere means rearrangement of arithmetic or logical expressions to run more efficiently be careful not to damage the compiler' ability to do such optimizations for you in an effort to optimize the expression yourself always check that your "optimizationsreally do improve the program by running the program before and after the change on suitable benchmark set of input many times have been wrong about the positive effects of code tuning in my own programs most often am wrong when try to optimize an expression it is hard to do better than the compiler the greatest time and space improvements come from better data structure or algorithm the final thought for this section is first tune the algorithmthen tune the code
20,149
empirical analysis this has focused on asymptotic analysis this is an analytic toolwhereby we model the key aspects of an algorithm to determine the growth rate of the algorithm as the input size grows as pointed out previouslythere are many limitations to this approach these include the effects at small problem sizedetermining the finer distinctions between algorithms with the same growth rateand the inherent difficulty of doing mathematical modeling for more complex problems an alternative to analytical approaches are empirical approaches the most obvious empirical approach is simply to run two competitors and see which performs better in this way we might overcome the deficiencies of analytical approaches be warned that comparative timing of programs is difficult businessoften subject to experimental errors arising from uncontrolled factors (system loadthe language or compiler usedetc the most important point is not to be biased in favor of one of the programs if you are biasedthis is certain to be reflected in the timings one look at competing software or hardware vendorsadvertisements should convince you of this the most common pitfall when writing two programs to compare their performance is that one receives more code-tuning effort than the other as mentioned in section code tuning can often reduce running time by factor of ten if the running times for two programs differ by constant factor regardless of input size ( their growth rates are the same)then differences in code tuning might account for any difference in running time be suspicious of empirical comparisons in this situation another approach to analysis is simulation the idea of simulation is to model the problem with computer program and then run it to get result in the context of algorithm analysissimulation is distinct from empirical comparison of two competitors because the purpose of the simulation is to perform analysis that might otherwise be too difficult good example of this appears in figure this figure shows the cost for inserting or deleting record from hash table under two different assumptions for the policy used to find free slot in the table the axes is the cost in number of hash table slots evaluatedand the axes is the percentage of slots in the table that are full the mathematical equations for these curves can be determinedbut this is not so easy reasonable alternative is to write simple variations on hashing by timing the cost of the program for various loading conditionsit is not difficult to construct plot similar to figure the purpose of this analysis is not to determine which approach to hashing is most efficientso we are not doing empirical comparison of hashing alternatives insteadthe purpose is to analyze the proper loading factor that would be used in an efficient hashing system to balance time cost versus hash table size (space cost
20,150
chap algorithm analysis further reading pioneering works on algorithm analysis include the art of computer programming by donald knuth [knu knu ]and the design and analysis of computer algorithms by ahohopcroftand ullman [ahu the alternate definition for ohm comes from [ahu the use of the notation " (nis in ( ( ))rather than the more commonly used " (no( ( )) derive from brassard and bratley [bb ]though certainly this use predates them good book to read for further information on algorithm analysis techniques is compared to whatby gregory rawlins [raw bentley [ben describes one problem in numerical analysis for whichbetween and the complexity of the best known algorithm had decreased from ( to ( for problem of size this is roughly equivalent to the speedup achieved from all advances in computer hardware during the same time period while the most important aspect of program efficiency is the algorithmmuch improvement can be gained from efficient coding of program as cited by frederick brooks in the mythical man-month [bro ]an efficient programmer can often produce programs that run five times faster than an inefficient programmereven when neither takes special efforts to speed up their code for excellent and enjoyable essays on improving your coding efficiencyand ways to speed up your code when it really matterssee the books by jon bentley [ben ben ben the situation described in example arose when we were working on the project reported on in [su as an interesting asidewriting correct binary search algorithm is not easy knuth [knu notes that while the first binary search was published in the first bug-free algorithm was not published until bentley ("writing correct programsin [ben ]has found that of the computer professionals he tested could not write bug-free binary search in two hours exercises for each of the five expressions of figure give the range of values of for which that expression is most efficient graph the following expressions for each expressionstate the range of values of for which that expression is the most efficient log log /
20,151
sec exercises arrange the following expressions by growth rate from slowest to fastest log log / see stirling' approximation in section for help in classifying (asuppose that particular algorithm has time complexity ( and that executing an implementation of it on particular machine takes seconds for inputs now suppose that we are presented with machine that is times as fast how many inputs could we process on the new machine in seconds(bsuppose that another algorithm has time complexity (nn and that executing an implementation of it on particular machine takes seconds for inputs now suppose that we are presented with machine that is times as fast how many inputs could we process on the new machine in seconds(ca third algorithm has time complexity ( executing an implementation of it on particular machine takes seconds for inputs given new machine that is times as fasthow many inputs could we process in seconds hardware vendor xyz corp claims that their latest computer will run times faster than that of their competitorprunesinc if the prunesinc computer can execute program on input of size in one hourwhat size input can xyz' computer execute in one hour for each algorithm with the following growth rate equationsn (afind growth rate that squares the run time when we double the input size that isif (nxthen ( nx (bfind growth rate that cubes the run time when we double the input size that isif (nxthen ( nx using the definition of big-ohshow that is in ( and that is in ( using the definitions of big-oh and ohmfind the upper and lower bounds for the following expressions be sure to state appropriate values for and (ac (bc (cc log (dc (awhat is the smallest integer such that (nk )
20,152
chap algorithm analysis (bwhat is the smallest integer such that log (nk ) (ais th( )explain why or why not (bis th( )explain why or why not for each of the following pairs of functionseither (nis in ( ( )) (nis in ohm( ( ))or (nth( ( )for each pairdetermine which relationship is correct justify your answerusing the method of limits discussed in section (af (nlog (nlog (bf (nng(nlog (cf (nlog ng(nlog (df (nng(nlog (ef (nn log ng(nlog (ff (nlog ( (log ) (gf ( (nlog (hf ( ( (if ( (nn log (jf ( ( (kf ( (nnn determine th for the following code fragments in the average case assume that all variables are of type int (aa cd (bsum for ( = < ++for ( = <nj++sum++(csum= for ( = < *ni++sum++(dfor ( = - ++for ( = + nj++tmp aa[ ][ ]aa[ ][jaa[ ][ ]aa[ ][itmp(esum for ( = <=ni++for ( = <=nj*= sum++
20,153
(fsum for ( = <=ni*= for ( = <=nj++sum++(gassume that array contains valuesrandom takes constant timeand sort takes log steps for ( = <ni++for ( = <nj++ [idsutil random( )sort( )(hassume array contains random permutation of the values from to sum for ( = <ni++for ( = [ ]!=ij++sum++(isum if (even( )for ( = <ni++sum++else sum sum show that big-theta notation (thdefines an equivalence relation on the set of functions give the best lower bound that you can for the following code fragmentas function of the initial value of while ( if (odd( ) else do you think that the upper bound is likely to be the same as the answer you gave for the lower bound does every algorithm have th running-time equationin other wordsare the upper and lower bounds for the running time (on any specified class of inputsalways the same does every problem for which there exists some algorithm have th runningtime equationin other wordsfor every problemand for any specified class of inputsis there some algorithm whose upper bound is equal to the problem' lower bound
20,154
chap algorithm analysis given an array storing integers ordered by valuemodify the binary search routine to return the position of the first integer with value in the situation where can appear multiple times in the array be sure that your algorithm is th(log )that isdo not resort to sequential search once an occurrence of is found given an array storing integers ordered by valuemodify the binary search routine to return the position of the integer with the greatest value less than when itself does not appear in the array return error if the least value in the array is greater than modify the binary search routine to support search in an array of infinite size in particularyou are given as input sorted array and key value to search for call the position of the smallest value in the array that is equal to or larger than provide an algorithm that can determine in (log ncomparisons in the worst case explain why your algorithm meets the required time bound it is possible to change the way that we pick the dividing point in binary searchand still get working search routine howeverwhere we pick the dividing point could affect the performance of the algorithm (aif we change the dividing point computation in function binary from ( )/ to ( (( )/ ))what will the worst-case running time be in asymptotic termsif the difference is only constant time factorhow much slower or faster will the modified program be compared to the original version of binary(bif we change the dividing point computation in function binary from ( )/ to what will the worst-case running time be in asymptotic termsif the difference is only constant time factorhow much slower or faster will the modified program be compared to the original version of binary design an algorithm to assemble jigsaw puzzle assume that each piece has four sidesand that each piece' final orientation is known (topbottometc assume that you have available function bool compare(piece apiece bside adthat can tellin constant timewhether piece connects to piece on ' side ad and ' opposite side bd the input to your algorithm should consist of an array of random piecesalong with dimensions and the algorithm should put the pieces in their correct positions in the array your algorithm should be as efficient as possible in the asymptotic sense write
20,155
summation for the running time of your algorithm on piecesand then derive closed-form solution for the summation can the average case cost for an algorithm be worse than the worst case costcan it be better than the best case costexplain why or why not prove that if an algorithm is th( ( )in the average casethen it is ohm( ( )in the worst case prove that if an algorithm is th( ( )in the average casethen it is ( ( )in the best case projects imagine that you are trying to store boolean valuesand must access them frequently compare the time required to access boolean values stored alternatively as single bit fielda charactera short integeror long integer there are two things to be careful of when writing your program firstbe sure that your program does enough variable accesses to make meaningful measurements single access is much smaller than the measurement rate for all four methods secondbe sure that your program spends as much time as possible doing variable accesses rather than other things such as calling timing functions or incrementing for loop counters implement sequential search and binary search algorithms on your computer run timings for each algorithm on arrays of size for ranging from to as large value as your computer' memory and compiler will allow for both algorithmsstore the values through in order in the arrayand use variety of random search values in the range to on each size graph the resulting times when is sequential search faster than binary search for sorted array implement program that runs and gives timings for the two fibonacci sequence functions provided in exercise graph the resulting running times for as many values of as your computer can handle
20,156
fundamental data structures
20,157
listsstacksand queues if your program needs to store few things -numberspayroll recordsor job descriptions for example -the simplest and most effective approach might be to put them in list only when you have to organize or search through large number of things do more sophisticated data structures usually become necessary (we will study how to organize and search through medium amounts of data in and and discuss how to deal with large amounts of data in - many applications don' require any form of searchand they do not require that any ordering be placed on the objects being stored some applications require processing in strict chronological orderperhaps processing objects in the order that they arrivedor perhaps processing objects in the reverse of the order that they arrived for all these situationsa simple list structure is appropriate this describes representations for lists in generalas well as two important list-like structures called the stack and the queue along with presenting these fundamental data structuresthe other goals of the are to( give examples of separating logical representation in the form of an adt from physical implementation for data structure ( illustrate the use of asymptotic analysis in the context of some simple operations that you might already be familiar with in this way you can begin to see how asymptotic analysis workswithout the complications that arise when analyzing more sophisticated algorithms and data structures ( introduce the concept and use of dictionaries we begin by defining an adt for lists in section two implementations for the list adt -the array-based list and the linked list -are covered in detail and their relative merits discussed sections and cover stacks and queuesrespectively sample implementations for each of these data structures are presented section presents the dictionary adt for storing and retrieving datawhich sets context for implementing search structures such as the binary search tree of section
20,158
chap listsstacksand queues lists we all have an intuitive understanding of what we mean by "list,so our first step is to define precisely what is meant so that this intuitive understanding can eventually be converted into concrete data structure and its operations perhaps the most important concept related to lists is that of position in other wordswe perceive that there is first element in the lista second elementand so on thuswe should view list as embodying the mathematical concepts of sequenceas defined in section we define list to be finiteordered sequence of data items known as elements "orderedin this definition means that each element has position in the list (we will not use "orderedin this context to mean that the list is sorted each list element has data type in the simple list implementations discussed in this all elements of the list have the same data typealthough there is no conceptual objection to lists whose elements have differing data types if the application requires it (see section the operations defined as part of the list adt do not depend on the elemental data type for examplethe list adt can be used for lists of integerslists of characterslists of payroll recordseven lists of lists list is said to be empty when it contains no elements the number of elements currently stored is called the length of the list the beginning of the list is called the headthe end of the list is called the tail there might or might not be some relationship between the value of an element and its position in the list for examplesorted lists have their elements positioned in ascending order of valuewhile unsorted lists have no particular relationship between element values and positions this section will consider only unsorted lists and treat the problems of how to create and search sorted lists efficiently when presenting the contents of listwe use the same notation as was introduced for sequences in section to be consistent with java array indexingthe first position on the list is denoted as thusif there are elements in the listthey are given positions through as ha an- the subscript indicates an element' position within the list using this notationthe empty list would appear as hi before selecting list implementationa program designer should first consider what basic operations the implementation must support our common intuition about lists tells us that list should be able to grow and shrink in size as we insert and remove elements we should be able to insert and remove elements from anywhere in the list we should be able to gain access to any element' valueeither to read it or to change it we must be able to create and clear (or reinitializelists it is also convenient to access the next or previous element from the "currentone
20,159
the next step is to define the adt for list object in terms of set of operations on that object we will use the java notation of an interface to formally define the list adt interface list defines the member functions that any list implementation inheriting from it must supportalong with their parameters and return types we increase the flexibility of the list adt by writing it as java generic true to the notion of an adtan interface does not specify how operations are implemented two complete implementations are presented later in this sectionboth of which use the same list adt to define their operationsbut they are considerably different in approaches and in their space/time tradeoffs figure presents our list adt class list is generic of one parameternamed serves as placeholder for whatever element type the user would like to store in list the comments given in figure describe precisely what each member function is intended to do howeversome explanation of the basic design is in order given that we wish to support the concept of sequencewith access to any position in the listthe need for many of the member functions such as insert and movetopos is clear the key design decision embodied in this adt is support for the concept of current position for examplemember movetostart sets the current position to be the first element on the listwhile methods next and prev move the current position to the next and previous elementsrespectively the intention is that any implementation for this adt support the concept of current position the current position is where any action such as insertion or deletion will take place since insertions take place at the current positionand since we want to be able to insert to the front or the back of the list as well as anywhere in betweenthere are actually possible "current positionswhen there are elements in the list it is helpful to modify our list display notation to show the position of the current element will use vertical barsuch as to indicate the list of four elementswith the current position being to the right of the bar at element given this configurationcalling insert with value will change the list to be if you examine figure you should find that the list member functions provided allow you to build list with elements in any desired orderand to access any desired position in the list you might have noticed that the clear method is not necessaryin that it could be implemented by means of the other member functions in the same asymptotic time it is included merely for convenience method getvalue returns reference to the current element it is considered violation of getvalue' preconditions to ask for the value of non-existent element ( the right partition must not be emptyin our concrete list imple
20,160
chap listsstacksand queues /*list adt *public interface list /*remove all contents from the listso it is once again empty client is responsible for reclaiming storage used by the list elements *public void clear()/*insert an element at the current location the client must ensure that the list' capacity is not exceeded @param item the element to be inserted *public void insert( item)/*append an element at the end of the list the client must ensure that the list' capacity is not exceeded @param item the element to be appended *public void append( item)/*remove and return the current element @return the element that was removed *public remove()/*set the current position to the start of the list *public void movetostart()/*set the current position to the end of the list *public void movetoend()/*move the current position one step left no change if already at beginning *public void prev()/*move the current position one step right no change if already at end *public void next()/*@return the number of elements in the list *public int length()/*@return the position of the current element *public int currpos()/*set current position @param pos the position to make current *public void movetopos(int pos)/*@return the current element *public getvalue()figure the adt for list
20,161
mentationsassertions are used to enforce such preconditions in commercial implementationsuch violations would be best implemented by the java exception mechanism list can be iterated through as shown in the following code fragment for ( movetostart() currpos()< length() next()it getvalue()dosomething(it)in this exampleeach element of the list in turn is stored in itand passed to the dosomething function the loop terminates when the current position reaches the end of the list the list class declaration presented here is just one of many possible interpretations for lists figure provides most of the operations that one naturally expects to perform on lists and serves to illustrate the issues relevant to implementing the list data structure as an example of using the list adtwe can create function to return true if there is an occurrence of given integer in the listand false otherwise the find method needs no knowledge about the specific list implementationjust the list adt /*@return true if "kis in list " "false otherwise *public static boolean find(list lint kint itfor ( movetostart() currpos()< length() next()it getvalue()if ( =itreturn true/found return false/ not found while this implementation for find could be written as generic with respect to the element typeit would still be limited in its ability to handle different data types stored on the list in particularit only works when the description for the object being searched for ( in the functionis of the same type as the objects themselves more typical situation is that we are searching for record that contains key field who' value matches similar functions to find and return composite element based on key value can be created using the list implementationbut to do so requires some agreement between the list adt and the find function on the concept of keyand on how keys may be compared this topic will be discussed in section
20,162
chap listsstacksand queues array-based list implementation there are two standard approaches to implementing liststhe array-based listand the linked list this section discusses the array-based approach the linked list is presented in section time and space efficiency comparisons for the two are discussed in section figure shows the array-based list implementationnamed alist alist inherits from abstract class list and so must implement all of the member functions of list class alist' private portion contains the data members for the array-based list these include listarraythe array which holds the list elements because listarray must be allocated at some fixed sizethe size of the array must be known when the list object is created note that an optional parameter is declared for the alist constructor with this parameterthe user can indicate the maximum number of elements permitted in the list if no parameter is giventhen it takes the value defaultsizewhich is assumed to be suitably defined constant value because each list can have differently sized arrayeach list must remember its maximum permitted size data member maxsize serves this purpose at any given time the list actually holds some number of elements that can be less than the maximum allowed by the array this value is stored in listsize data member curr stores the current position because listarraymaxsizelistsizeand curr are all declared to be privatethey may only be accessed by methods of class alist class alist stores the list elements in contiguous array positions array positions correspond to list positions in other wordsthe element at position in the list is stored at array cell the head of the list is always at position this makes random access to any element in the list quite easy given some position in the listthe value of the element in that position can be accessed directly thusaccess to any element using the movetopos method followed by the getvalue method takes th( time because the array-based list implementation is defined to store list elements in contiguous cells of the arraythe insertappendand remove methods must maintain this property inserting or removing elements at the tail of the list is easyand the append operation takes th( time howeverif we wish to insert an element at the head of the listall elements currently in the list must shift one position toward the tail to make roomas illustrated by figure this process takes th(ntime if there are elements already in the list if we wish to insert at position within list of elementsthen elements must shift toward the tail removing an element from the head of the list is similar in that all remaining
20,163
sec lists /*array-based list implementation *class alist implements list private static final int defaultsize /default size private int maxsize/maximum size of list private int listsize/number of list items now private int curr/position of current element private [listarray/array holding list elements /*constructors */*create list with the default capacity *alist(this(defaultsize)/*create new list object @param size max number of elements list can contain *@suppresswarnings("unchecked"/generic array allocation alist(int sizemaxsize sizelistsize curr listarray ( [])new object[size]/create listarray public void clear(listsize curr /reinitialize the list /simply reinitialize values /*insert "itat current position *public void insert( itassert listsize maxsize "list capacity exceeded"for (int =listsizei>curri--/shift elements up listarray[ilistarray[ - ]/to make room listarray[curritlistsize++/increment list size public void append( it/append "itassert listsize maxsize "list capacity exceeded"listarray[listsize++it/remove and return the current element public remove(if ((curr=listsize)/no current element return nulle it listarray[curr]/copy the element for(int =curri<listsize- ++/shift them down listarray[ilistarray[ + ]listsize--/decrement size return itfigure an array-based list implementation
20,164
chap listsstacksand queues public void movetostart(curr /reset position public void movetoend(curr listsize/reset public void prev(if (curr ! curr--/back up public void next(if (curr listsizecurr++/next /return list size public int length(return listsize/return current position public int currpos(return curr/set current list position to "pospublic void movetopos(int posassert (pos>= &(pos<=listsize"pos out of range"curr pospublic getvalue(/return current element assert (curr>= )&&(curr<listsize"no current element"return listarray[curr]figure (continuedelements in the array must shift toward the head by one position to fill in the gap to remove the element at position in elements must shift toward the head in the average caseinsertion or removal requires moving half of the elementswhich is th(nmost of the other member functions for class alist simply access the current list element or move the current position such operations all require th( time aside from insert and removethe only other operations that might require more than constant time are the constructorthe destructorand clear these three member functions each make use of the system free-store operation new as discussed further in section system free-store operations can be expensive linked lists the second traditional approach to implementing lists makes use of pointers and is usually called linked list the linked list uses dynamic memory allocationthat isit allocates memory for new list elements as needed linked list is made up of series of objectscalled the nodes of the list because list node is distinct object (as opposed to simply cell in an array)it is good practice to make separate list node class an additional benefit to creating
20,165
sec lists insert ( ( (cfigure inserting an element at the head of an array-based list requires shifting all existing elements in the array by one position toward the tail (aa list containing five elements before inserting an element with value (bthe list after shifting all existing elements one position to the right (cthe list after has been inserted in array position shading indicates the unused part of the array list node class is that it can be reused by the linked implementations for the stack and queue data structures presented later in this figure shows the implementation for list nodescalled the link class objects in the link class contain an element field to store the element valueand next field to store pointer to the next node on the list the list built from such nodes is called singly linked listor one-way listbecause each list node has single pointer to the next node on the list the link class is quite simple there are two forms for its constructorone with an initial element value and one without because the link class is also used by the stack and queue implementations presented laterits data members are made public while technically this is breaking encapsulationin practice the link class should be implemented as private class of the linked list (or stack or queueimplementationand thus not visible to the rest of the program figure (ashows graphical depiction for linked list storing four integers the value stored in pointer variable is indicated by an arrow "pointingto something java uses the special symbol null for pointer value that points nowheresuch as for the last list node' next field null pointer is indicated graphically by diagonal slash through pointer variable' box the vertical line between the nodes labeled and in figure (aindicates the current position the first link node of the list is accessed from pointer named head to speed access to the end of the listin particular to allow the append method to be performed in constant timea pointer named tail is also kept to the last link
20,166
chap listsstacksand queues class link private elementprivate link next/singly linked list node /value for this node /pointer to next node in list /constructors link( itlink nextvalelement itnext nextvallink(link nextvalnext nextvallink next(return nextlink setnext(link nextvalreturn next nextvale element(return elemente setelement( itreturn element it/class link figure simple singly linked list node implementation head curr tail (ahead tail curr (bfigure illustration of faulty linked-list implementation where curr points directly to the current node (alinked list prior to inserting element with value (bdesired effect of inserting element with value of the list the position of the current element is indicated by another pointernamed curr finallybecause there is no simple way to compute the length of the list simply from these three pointersthe list length must be stored explicitlyand updated by every operation that modifies the list size the value cnt stores the length of the list note that llist' constructor maintains the optional parameter for minimum list size introduced for class alist this is done simply to keep the calls to the constructor the same for both variants because the linked list class does not need to declare fixed-size array when the list is createdthis parameter is unnecessary for linked lists it is ignored by the implementation
20,167
sec lists curr tail head figure initial state of linked list when using header node key design decision for the linked list implementation is how to represent the current position the most reasonable choices appear to be pointer to the current element but there is big advantage to making curr point to the element preceding the current element figure (ashows the list' curr pointer pointing to the current element the vertical line between the nodes containing and indicates the logical position of the current element consider what happens if we wish to insert new node with value into the list the result should be as shown in figure (bhoweverthere is problem to "splicethe list node containing the new element into the listthe list node storing must have its next pointer changed to point to the new node unfortunatelythere is no convenient access to the node preceding the one pointed to by curr howeverif curr points directly to the preceding elementthere is no difficulty in adding new element after curr see exercise for further discussion of why making curr point directly to the current element fails unfortunatelywe encounter number of problems when the list is emptyor when the current position is at an end of the list in particularwhen the list is empty we have no element for headtailand curr to point to one solution is to implement number of special cases in the implementations for insert and remove this increases code complexitymaking it harder to understandand thus increases the chance of introducing programming bug these special cases can be eliminated by implementing linked lists with special header node as the first node of the list this header node is link node like any otherbut its value is ignored and it is not considered to be an actual element of the list the header node saves coding effort because we no longer need to consider special cases for empty lists or when the current position is at one end of the list the cost of this simplification is the space for the header node howeverthere are space savings due to smaller code sizebecause statements to handle the special cases are omitted in practicethis reduction in code size typically saves more space than that required for the header nodedepending on the number of lists created figure shows the state of an initialized or empty list when using header node figure shows the insertion example of figure using header node and the convention that curr points to the node preceding the current node
20,168
chap listsstacksand queues head curr tail (ahead curr tail (bfigure insertion using header nodewith curr pointing one node head of the current element (alinked list before insertion the current node contains (blinked list after inserting the node containing figure shows the definition for the linked list classnamed llist class llist inherits from the abstract list class and thus must implement all of class list' member functions implementation for most member functions of the list class is straightforward howeverinsert and remove should be studied carefully inserting new element is three-step process firstthe new list node is created and the new element is stored into it secondthe next field of the new list node is assigned to point to the current node (the one (afterthe node that curr points tothirdthe next field of node pointed to by curr is assigned to point to the newly inserted node the following line in the insert method of figure actually does all three of these steps curr setnext(new link(itcurr next()))operator new creates the new link node and calls the constructor for the link classwhich takes two parameters the first is the element the second is the value to be placed in the list node' next fieldin this case "curr next figure illustrates this three-step process once the new node is addedtail is pushed forward if the new element was added to the end of the list insertion requires th( time removing node from the linked list requires only that the appropriate pointer be redirected around the node to be deleted this memory will eventually be reclaimed by the garbage collector the following lines from the remove method of figure do precisely this it curr next(element()/remember value curr setnext(curr next(next())/remove from list
20,169
sec lists /linked list implementation class llist implements list private link head/pointer to list header private link tail/pointer to last element protected link curr/access to current element int cnt/size of list //constructors llist(int sizethis()/constructor -ignore size llist(curr tail head new link(null)/create header cnt public void clear(/remove all elements head setnext(null)/drop access to links curr tail head new link(null)/create header cnt /insert "itat current position public void insert( itcurr setnext(new link(itcurr next()))if (tail =currtail curr next()/new tail cnt++public void append( it/append "itto list tail tail setnext(new link(itnull))cnt++/remove and return current element public remove(if (curr next(=nullreturn null/nothing to remove it curr next(element()/remember value if (tail =curr next()tail curr/removed last curr setnext(curr next(next())/remove from list cnt--/decrement count return it/return value figure linked list implementation
20,170
chap listsstacksand queues public void movetostart(curr headpublic void movetoend(curr tail/set curr at list start /set curr at list end /move curr one step leftno change if already at front public void prev(if (curr =headreturn/no previous element link temp head/march down list until we find the previous element while (temp next(!currtemp temp next()curr temp/move curr one step rightno change if already at end public void next(if (curr !tailcurr curr next()public int length(return cnt/return length /return the position of the current element public int currpos(link temp headint ifor ( = curr !tempi++temp temp next()return /move down list to "posposition public void movetopos(int posassert (pos>= &(pos<=cnt"position out of range"curr headfor(int = <posi++curr curr next()public getvalue(/return current element if(curr next(=nullreturn nullreturn curr next(element()figure (continued
20,171
sec lists curr insert (acurr (bfigure the linked list insertion process (athe linked list before insertion (bthe linked list after insertion marks the element field of the new link node marks the next field of the new link nodewhich is set to point to what used to be the current node (the node with value marks the next field of the node preceding the current position it used to point to the node containing now it points to the new node containing curr (acurr it (bfigure the linked list removal process (athe linked list before removing the node with value (bthe linked list after removal marks the list node being removed it is set to point to the element marks the next field of the preceding list nodewhich is set to point to the node following the one being deleted
20,172
chap listsstacksand queues figure illustrates the remove method removing an element requires th( time method next simply moves curr one position toward the tail of the listwhich takes th( time method prev moves curr one position toward the head of the listbut its implementation is more difficult in singly linked listthere is no pointer to the previous node thusthe only alternative is to march down the list from the beginning until we reach the current node (being sure always to remember the node before itbecause that is what we really wantthis takes th(ntime in the average and worst cases implementation of method movetopos is similar in that finding the ith position requires marching down positions from the head of the listtaking th(itime implementations for the remaining operations are straightforwardeach requiring th( time freelists the new operator is relatively expensive to use garbage collection is also expensive section discusses how general-purpose memory manager can be implemented the problem is that free-store routines must be capable of handling requests to and from free store with no particular patternas well as requests of vastly different sizes most runtime environments today provide reasonable implementations for their free-store operators howeverthe requirement that free-store managers be able to handle any pattern of new operationscombined with unpredictable freeing of space by the garbage collectormakes them inefficient compared to what might be implemented for more controlled patterns of memory access the conditions under which list nodes are created and deleted in linked list implementation allow the link class programmer to provide simple but efficient memory management routines in place of the system-level free-store operators instead of making repeated calls to newthe link class can handle its own freelist freelist holds those list nodes that are not currently being used when node is deleted from linked listit is placed at the head of the freelist when new element is to be added to linked listthe freelist is checked to see if list node is available if sothe node is taken from the freelist if the freelist is emptythe standard new operator must then be called freelists are particularly useful for linked lists that periodically grow and then shrink the freelist will never grow larger than the largest size yet reached by the linked list requests for new nodes (after the list has shrunkcan be handled by the freelist
20,173
sec lists /singly linked list node with freelist support class link private element/value for this node private link next/point to next node in list /constructors link( itlink nextvalelement itnext nextvallink(link nextvalnext nextvallink next(return nextlink setnext(link nextvalreturn next nextvale element(return elemente setelement( itreturn element it/extensions to support freelists static link freelist null/freelist for the class /get new link static link get( itlink nextvalif (freelist =nullreturn new link(itnextval)/get from "newlink temp freelist/get from freelist freelist freelist next()temp setelement(it)temp setnext(nextval)return tempvoid release(element nullnext freelistfreelist this/class link /return link to freelist /drop reference to the element figure implementation for the link class with freelist the static declaration for member freelist means that all link class objects share the same freelist pointer variable instead of each object storing its own copy in the implementation shown herethe link class is augmented with methods get and release figure shows the reimplementation for the link class to support these methods note how simple they arebecause they need only remove and add an element to the front of the freelistrespectively the freelist methods get and release both run in th( timeexcept in the case where the freelist is exhausted and the new operation must be called
20,174
chap listsstacksand queues in figure you should note the use of the static definition for the freelist header the purpose of the keyword static is to create single variable shared among all instances of the link nodes we want only single freelist for all link nodes of given type program might create multiple lists if they are all of the same type (that istheir element types are the same)then they can and should share the same freelist this will happen with the implementation of figure if lists are created that have different element typesbecause this code is implemented with genericthe need for different list implementations will be discovered by the runtime environment separate versions of the list class will be generated for each element type thuseach element type will also get its own separate copy of the link class and each distinct link class implementation will get separate freelist let' consider more complex situation where we want separate freelistsbut we don' know this until runtime for exampleperhaps we are using lists to store variable-length strings given node gets space allocated for string of specific length we' like to be able to reuse the nodes by placing them on freelistinstead of relying on the system free store operators but we cannot reuse given list node unless the size allocated for its string matches the length of the string we want to store in this node thuseach specific node size must be stored on its own freelist that isthe nodes for strings of length one are stored on one freelistthe nodes for strings of length two on another freelistand so on in this wayits easy to find node of the proper size unfortunatelywe don' know in advance what the various sizes of strings will be if we want to support long stringsthen there could be thousands of different node sizesmany of which are not used in any particular run of the program thuswe do not want to allocate freelists in advance for each potential node length on the other handwe need to make sure no more than one copy of the freelist for given size is created we can modify our freelist free-store operations to request the appropriate freelist this access function will search for the proper freelist if it existsthat freelist is used if notthat freelist is created comparison of list implementations now that you have seen two substantially different implementations for listsit is natural to ask which is better in particularif you must implement list for some taskwhich implementation should you choosearray-based lists have the disadvantage that their size must be predetermined before the array can be allocated array-based lists cannot grow beyond their pre
20,175
sec lists determined size whenever the list contains only few elementsa substantial amount of space might be tied up in largely empty array linked lists have the advantage that they only need space for the objects actually on the list there is no limit to the number of elements on linked listas long as there is free-store memory available the amount of space required by linked list is th( )while the space required by the array-based list implementation is ohm( )but can be greater array-based lists have the advantage that there is no wasted space for an individual element linked lists require that pointer be added to every list node if the element size is smallthen the overhead for links can be significant fraction of the total storage when the array for the array-based list is completely filledthere is no storage overhead the array-based list will then be more space efficientby constant factorthan the linked implementation simple formula can be used to determine whether the array-based list or linked list implementation will be more space efficient in particular situation call the number of elements currently in the listp the size of pointer in storage units (typically four bytes) the size of data element in storage units (this could be anythingfrom one bit for boolean variable on up to thousands of bytes or more for complex records)and the maximum number of list elements that can be stored in the array the amount of space required for the array-based list is deregardless of the number of elements actually stored in the list at any given time the amount of space required for the linked list is ( ethe smaller of these expressions for given value determines the more space-efficient implementation for elements in generalthe linked implementation requires less space than the array-based implementation when relatively few elements are in the list converselythe array-based implementation becomes more space efficient when the array is close to full using the equationwe can solve for to determine the break-even point beyond which the array-based implementation is more space efficient in any particular situation this occurs when de/( eif ethen the break-even point is at / this would happen if the element field is either four-byte int value or pointerand the next field is typical fourbyte pointer that isthe array-based implementation would be more efficient (if the link field and the element field are the same sizewhenever the array is more than half full as rule of thumblinked lists are better when implementing lists whose number of elements varies widely or is unknown array-based lists are generally more space efficient when the user knows in advance approximately how large the list will become
20,176
chap listsstacksand queues array-based lists are faster for random access by position positions can easily be adjusted forwards or backwards by the next and prev methods these operations always take th( time in contrastsingly linked lists have no explicit access to the previous elementand access by position requires that we march down the list from the front (or the current positionto the specified position both of these operations require th(ntime in the average and worst casesif we assume that each position on the list is equally likely to be accessed on any call to prev or movetopos given pointer to suitable location in the listthe insert and remove methods for linked lists require only th( time array-based lists must shift the remainder of the list up or down within the array this requires th(ntime in the average and worst cases for many applicationsthe time to insert and delete elements dominates all other operations for this reasonlinked lists are often preferred to array-based lists when implementing the array-based listan implementor could allow the size of the array to grow and shrink depending on the number of elements that are actually stored this data structure is known as dynamic array for examplethe java vector class implements dynamic array dynamic arrays allow the programmer to get around the limitation on the standard array that its size cannot be changed once the array has been created this also means that space need not be allocated to the dynamic array until it is to be used the disadvantage of this approach is that it takes time to deal with space adjustments on the array each time the array grows in sizeits contents must be copied good implementation of the dynamic array will grow and shrink the array in such way as to keep the overall cost for series of insert/delete operations relatively inexpensiveeven though an occasional insert/delete operation might be expensive to analyze the cost of dynamic array operationswe need to use technique known as amortized analysiswhich is discussed in section element implementations list users must decide whether they wish to store copy of any given element on each list that contains it for small elements such as an integerthis makes sense if the elements are payroll recordsit might be desirable for the list node to store reference to the record rather than store copy of the record itself this change would allow multiple list nodes (or other data structuresto point to the same recordrather than make repeated copies of the record not only might this save spacebut it also means that modification to an element' value is automatically reflected at all locations where it is referenced the disadvantage of storing
20,177
pointer to each element is that the pointer requires space of its own if elements are never duplicatedthen this additional space adds unnecessary overhead java most naturally stores references to objectsmeaning that only single copy of an object such as payroll record will be maintainedeven if it is on multiple lists whether it is more advantageous to use references to shared elements or separate copies depends on the intended application in generalthe larger the elements and the more they are duplicatedthe more likely that references to shared elements is the better approach second issue faced by implementors of list class (or any other data structure that stores collection of user-defined data elementsis whether the elements stored are all required to be of the same type this is known as homogeneity in data structure in some applicationsthe user would like to define the class of the data element that is stored on given listand then never permit objects of different class to be stored on that same list in other applicationsthe user would like to permit the objects stored on single list to be of differing types for the list implementations presented in this sectionthe compiler requires that all objects stored on the list be of the same type besides java genericsthere are other techniques that implementors of list class can use to ensure that the element type for given list remains fixedwhile still permitting different lists to store different element types one approach is to store an object of the appropriate type in the header node of the list (perhaps an object of the appropriate type is supplied as parameter to the list constructor)and then check that all insert operations on that list use the same element type the third issue that users of the list implementations must face is primarily of concern when programming in languages that do not support automatic garbage collection that is how to deal with the memory of the objects stored on the list when the list is deleted or the clear method is called the list destructor and the clear method are problematic in that there is potential that they will be misused deleting listarray in the array-based implementationor deleting link node in the linked list implementationmight remove the only reference to an objectleaving its memory space inaccessible unfortunatelythere is no way for the list implementation to know whether given object is pointed to in another part of the program or not thusthe user of the list must be responsible for deleting these objects when that is appropriate doubly linked lists the singly linked list presented in section allows for direct access from list node only to the next node in the list doubly linked list allows convenient
20,178
chap listsstacksand queues head curr tail figure doubly linked list class dlink private elementprivate dlink nextprivate dlink prev/doubly linked list node /value for this node /pointer to next node in list /pointer to previous node /constructors dlink( itdlink pdlink nelement itprev pnext ndlink(dlink pdlink nprev pnext ndlink next(return nextdlink setnext(dlink nextvalreturn next nextvaldlink prev(return prevdlink setprev(dlink prevvalreturn prev prevvale element(return elemente setelement( itreturn element it/class dlink figure doubly linked list node implementation with freelist access from list node to the next node and also to the preceding node on the list the doubly linked list node accomplishes this in the obvious way by storing two pointersone to the node following it (as in the singly linked list)and second pointer to the node preceding it the most common reason to use doubly linked list is because it is easier to implement than singly linked list while the code for the doubly linked implementation is little longer than for the singly linked versionit tends to be bit more "obviousin its intentionand so easier to implement and debug figure illustrates the doubly linked list concept like our singly linked list implementationthe doubly linked list implementation makes use of header node we also add tailer node to the end of the list the tailer is similar to the headerin that it is node that contains no valueand it always exists when the doubly linked list is initializedthe header and tailer nodes are created data member head points to the header nodeand tail points to the tailer node the purpose of these nodes is to simplify the insertappendand remove methods by eliminating all need for special-case code when the list is empty
20,179
/insert "itat current position public void insert( itcurr setnext(new dlink(itcurrcurr next()))curr next(next(setprev(curr next())cnt++public void append( it/append "itto list tail setprev(new dlink(ittail prev()tail))tail prev(prev(setnext(tail prev())cnt++/remove and return first element in right partition public remove(if (curr next(=tailreturn null/nothing to remove it curr next(element()/remember value curr next(next(setprev(curr)curr setnext(curr next(next())/remove from list cnt--/decrement the count return it/return value removed /move curr one step leftno change if at front public void prev(if (curr !head/can' back up from list head curr curr prev()figure implementations for doubly linked list class insertappendremoveand prev methods whether list implementation is doubly or singly linked should be hidden from the list class user figure shows the complete implementation for link class to be used with doubly linked lists this code is little longer than that for the singly linked list node implementation since the doubly linked list nodes have an extra data member figure shows the implementation for the insertappendremoveand prev doubly linked list methods the class declaration and the remaining member functions for the doubly linked list class are nearly identical to those of figures the insert method is especially simple for our doubly linked list implementationbecause most of the work is done by the node' constructor figure shows the list before and after insertion of node with value
20,180
chap listsstacksand queues curr insert (acurr (bfigure insertion for doubly linked lists the labels and correspond to assignments done by the linked list node constructor marks the assignment to curr->next marks the assignment to the prev pointer of the node following the newly inserted node the three parameters to the new operator allow the list node class constructor to set the elementprevand next fieldsrespectivelyfor the new link node the new operator returns pointer to the newly created node the nodes to either side have their pointers updated to point to the newly created node the existence of the header and tailer nodes mean that there are no special cases to be worried about when inserting into an empty list the list class append method from figure is also simple againthe link class constructor sets the elementprevand next fields of the node when the new operator is executed method remove (illustrated by figure is straightforwardthough the code is somewhat longer firstthe variable it is assigned the value being removed note that we must separate the elementwhich is returned to the callerfrom the link object the following lines then adjust the list it curr next(element()/remember value curr next(next(setprev(curr)curr setnext(curr next(next())/remove from list the second line makes the next node' prev pointer point to the left of the node being removed finallythe next field of the node preceding the one being deleted is adjusted the final steps of method remove are to update the list length and return the value of the deleted element
20,181
sec lists curr (acurr it (bfigure doubly linked list removal element it stores the element of the node being removed then the nodes to either side have their pointers adjusted the only disadvantage of the doubly linked list as compared to the singly linked list is the additional space used the doubly linked list requires two pointers per nodeand so in the implementation presented it requires twice as much overhead as the singly linked list example there is space-saving technique that can be employed to eliminate the additional space requirementthough it will complicate the implementation and be somewhat slower thusthe technique is an example of space/time tradeoff it is based on observing thatif we store the sum of two valuesthen we can get either value back by subtracting the other that isif we store in variable cthen and of courseto recover one of the values out of the stored summationthe other value must be supplied pointer to the first node in the listalong with the value of one of its two link fieldswill allow access to all of the remaining nodes of the list in order this is because the pointer to the node must be the same as the value of the following node' prev pointeras well as the previous node' next pointer it is possible to move down the list breaking apart the summed link fields as though you were opening zipper details for implementing this variation are left as an exercise the principle behind this technique is worth rememberingbecause it has many applications the following code fragment will swap the contents of two variables without using temporary variable (at the cost of three arithmetic operations
20,182
chap listsstacksand queues bb /now contains original value of /now contains original value of similar effect can be had by using the exclusive-or operator this fact is widely used in computer graphics region of the computer screen can be highlighted by xoring the outline of box around it xoring the box outline second time restores the original contents of the screen stacks the stack is list-like structure in which elements may be inserted or removed from only one end while this restriction makes stacks less flexible than listsit also makes stacks both efficient (for those operations they can doand easy to implement many applications require only the limited form of insert and remove operations that stacks provide in such casesit is more efficient to use the simpler stack data structure rather than the generic list for examplethe freelist of section is really stack despite their restrictionsstacks have many uses thusa special vocabulary for stacks has developed accountants used stacks long before the invention of the computer they called the stack "lifolistwhich stands for "last-infirstout note that one implication of the lifo policy is that stacks remove elements in reverse order of their arrival it is traditional to call the accessible element of the stack the top element elements are not said to be insertedinstead they are pushed onto the stack when removedan element is said to be popped from the stack figure shows sample stack adt as with liststhere are many variations on stack implementation the two approaches presented here are array-based and linked stackswhich are analogous to array-based and linked listsrespectively array-based stacks figure shows complete implementation for the array-based stack class as with the array-based list implementationlistarray must be declared of fixed size when the stack is created in the stack constructorsize serves to indicate this size method top acts somewhat like current position value (because the "currentposition is always at the top of the stack)as well as indicating the number of elements currently in the stack
20,183
sec stacks /*stack adt *public interface stack /*reinitialize the stack the user is responsible for reclaiming the storage used by the stack elements *public void clear()/*push an element onto the top of the stack @param it the element being pushed onto the stack *public void push( it)/*remove and return the element at the top of the stack @return the element at the top of the stack *public pop()/*@return copy of the top element *public topvalue()/*@return the number of elements in the stack *public int length()}figure the stack adt the array-based stack implementation is essentially simplified version of the array-based list the only important design decision to be made is which end of the array should represent the top of the stack one choice is to make the top be at position in the array in terms of list functionsall insert and remove operations would then be on the element in position this implementation is inefficientbecause now every push or pop operation will require that all elements currently in the stack be shifted one position in the arrayfor cost of th(nif there are elements the other choice is have the top element be at position when there are elements in the stack in other wordsas elements are pushed onto the stackthey are appended to the tail of the list method pop removes the tail element in this casethe cost for each push or pop operation is only th( for the implementation of figure top is defined to be the array index of the first free position in the stack thusan empty stack has top set to the first available free position in the array (alternativelytop could have been defined to be the index for the top element in the stackrather than the first free position if this had been donethe empty list would initialize top as - methods push and pop simply place an element intoor remove an element fromthe array position indicated by top because top is assumed to be at the first free positionpush first inserts its value into the top position and then increments topwhile pop first decrements top and then removes the top element
20,184
chap listsstacksand queues /*array-based stack implementation *class astack implements stack private static final int defaultsize private int maxsizeprivate int topprivate [listarray/maximum size of stack /index for top object /array holding stack /constructors astack(this(defaultsize)@suppresswarnings("unchecked"/generic array allocation astack(int sizemaxsize sizetop listarray ( [])new object[size]/create listarray public void clear(top /reinitialize stack public void push( it/push "itonto stack assert top !maxsize "stack is full"listarray[top++itpublic pop(/pop top element assert top ! "stack is empty"return listarray[--top]public topvalue(/return top element assert top ! "stack is empty"return listarray[top- ]public int length(return top/return length figure array-based stack class implementation
20,185
sec stacks /linked stack implementation class lstack implements stack private link top/pointer to first element private int size/number of elements //constructors public lstack(top nullsize public lstack(int sizetop nullsize /reinitialize stack public void clear(top nullsize public void push( it/put "iton stack top new link(ittop)size++public pop(/remove "itfrom stack assert top !null "stack is empty" it top element()top top next()size--return itpublic topvalue(/return top value assert top !null "stack is empty"return top element()public int length(return size/return length figure linked stack class implementation linked stacks the linked stack implementation is simplified version of the linked list implementation the freelist of section is an example of linked stack elements are inserted and removed only from the head of the list the header node is not used because no special-case code is required for lists of zero or one elements figure shows the complete class implementation for the linked stack the only data member is topa pointer to the first (toplink node of the stack method push first modifies the next field of the newly created link node to point to the top of the stack and then sets top to point to the new link node method pop is also quite simple the variable temp stores the value of the top nodewhile ltemp keeps link to the top node as it is removed from the stack the stack is updated by setting top to point to the next element in the stack the old top node
20,186
chap listsstacksand queues top top figure two stacks implemented within in single arrayboth growing toward the middle is then returned to free store (or the freelist)and the element value is returned as the value of the pop method comparison of array-based and linked stacks all operations for the array-based and linked stack implementations take constant timeso from time efficiency perspectiveneither has significant advantage another basis for comparison is the total space required the analysis is similar to that done for list implementations the array-based stack must declare fixed-size array initiallyand some of that space is wasted whenever the stack is not full the linked stack can shrink and grow but requires the overhead of link field for every element when multiple stacks are to be implementedit is possible to take advantage of the one-way growth of the array-based stack this can be done by using single array to store two stacks one stack grows inward from each end as illustrated by figure hopefully leading to less wasted space howeverthis only works well when the space requirements of the two stacks are inversely correlated in other wordsideally when one stack growsthe other will shrink this is particularly effective when elements are taken from one stack and given to the other if instead both stacks grow at the same timethen the free space in the middle of the array will be exhausted quickly implementing recursion perhaps the most common computer application that uses stacks is not even visible to its users this is the implementation of subroutine calls in most programming language runtime environments subroutine call is normally implemented by placing necessary information about the subroutine (including the return addressparametersand local variablesonto stack this information is called an activation record further subroutine calls add to the stack each return from subroutine pops the top activation record off the stack figure illustrates the implementation of the recursive factorial function of section from the runtime environment' point of view
20,187
sec stacks currptr currptr currptr call fact( currptr currptr currptr currptr currptr currptr call fact( call fact( call fact( currptr currptr return currptr currptr currptr currptr return return currptr return figure implementing recursion with stack values indicate the address of the program instruction to return to after completing the current function call on each recursive function call to fact (from section )both the return address and the current value of must be saved each return from fact pops the top activation record off the stack consider what happens when we call fact with the value we use to indicate the address of the program instruction where the call to fact is made thusthe stack must first store the address band the value is passed to fact nexta recursive call to fact is madethis time with value we will name the program address from which the call is made the address along with the current value for (which is )is saved on the stack function fact is invoked with input parameter in similar manneranother recursive call is made with input parameter requiring that the address from which the call is made (say and the current value for (which is are stored on the stack final recursive call with input parame
20,188
chap listsstacksand queues ter is maderequiring that the stack store the calling address (say and current value (which is at this pointwe have reached the base case for factand so the recursion begins to unwind each return from fact involves popping the stored value for from the stackalong with the return address from the function call the return value for fact is multiplied by the restored value for nand the result is returned because an activation record must be created and placed onto the stack for each subroutine callmaking subroutine calls is relatively expensive operation while recursion is often used to make implementation easy and clearsometimes you might want to eliminate the overhead imposed by the recursive function calls in some casessuch as the factorial function of section recursion can easily be replaced by iteration example as simple example of replacing recursion with stackconsider the following non-recursive version of the factorial function static long fact(int /compute /to fit nin long variablerequire assert ( > &( < " out of range"/make stack just big enough stack new astack( )while ( push( --)long result while ( length( result result pop()return resultherewe simply push successively smaller values of onto the stack until the base case is reachedthen repeatedly pop off the stored values and multiply them into the result in practicean iterative form of the factorial function would be both simpler and faster than the version shown in example unfortunatelyit is not always possible to replace recursion with iteration recursionor some imitation of itis necessary when implementing algorithms that require multiple branching such as in the towers of hanoi algorithmor when traversing binary tree the mergesort and quicksort algorithms of are also examples in which recursion is required fortunatelyit is always possible to imitate recursion with stack let us now turn to non-recursive version of the towers of hanoi functionwhich cannot be done iteratively
20,189
sec stacks example the toh function shown in figure makes two recursive callsone to move rings off the bottom ringand another to move these rings back to the goal pole we can eliminate the recursion by using stack to store representation of the three operations that toh must performtwo recursive calls and move operation to do sowe must first come up with representation of the various operationsimplemented as class whose objects will be stored on the stack here is such class class tohobj public operation oppublic int numpublic pole startgoaltemptohobj(operation oint npole spole gpole top onum nstart sgoal gtemp ttohobj(operation opole spole gop ostart sgoal /move class tohobj stores five valuesan operation field (indicating either move or new toh operation)the number of ringsand the three poles note that the move operation actually needs only to store information about two poles thusthere are two constructorsone to store the state when imitating recursive calland one to store the state for move operation the non-recursive version of toh can now be presented
20,190
chap listsstacksand queues static void toh(int npole startpole goalpole temp/make stack just big enough stack new astack( * + ) push(new tohobj(operation tohnstartgoaltemp))while ( length( tohobj it pop()/get next task if (it op =operation move/do move move(it startit goal)else if (it num /imitate toh recursive /solution (in reverses push(new tohobj(operation tohit num- it tempit goalit start)) push(new tohobj(operation moveit startit goal))/ move to do push(new tohobj(operation tohit num- it startit tempit goal))we first define an enumerated type called tohopwith two values move and tohto indicate calls to the move function and recursive calls to tohrespectively note that an array-based stack is usedbecause we know that the stack will need to store exactly elements the new version of toh begins by placing on the stack description of the initial problem of rings the rest of the function is simply while loop that pops the stack and executes the appropriate operation in the case of toh operation (for )we store on the stack representations for the three operations executed by the recursive version howeverthese operations must be placed on the stack in reverse orderso that they will be popped off in the correct order some "naturally recursiveapplications lend themselves to efficient implementation with stackbecause the amount of information needed to describe subproblem is small for examplesection discusses stack-based implementation for quicksort queues like the stackthe queue is list-like structure that provides restricted access to its elements queue elements may only be inserted at the back (called an enqueue
20,191
sec queues /*queue adt *public interface queue /*reinitialize the queue the user is responsible for reclaiming the storage used by the queue elements *public void clear()/*place an element at the rear of the queue @param it the element being enqueued *public void enqueue( it)/*remove and return element at the front of the queue @return the element at the front of the queue *public dequeue()/*@return the front element *public frontvalue()/*@return the number of elements in the queue *public int length()figure the java adt for queue operationand removed from the front (called dequeue operationqueues operate like standing in line at movie theater ticket counter if nobody cheatsthen newcomers go to the back of the line the person at the front of the line is the next to be served thusqueues release their elements in order of arrival accountants have used queues since long before the existence of computers they call queue "fifolistwhich stands for "first-infirst-out figure shows sample queue adt this section presents two implementations for queuesthe array-based queue and the linked queue array-based queues the array-based queue is somewhat tricky to implement effectively simple conversion of the array-based list implementation is not efficient assume that there are elements in the queue by analogy to the array-based list implementationwe could require that all elements of the queue be stored in the first positions of the array if we choose the rear element of the queue to be in position then dequeue operations require only th( time because the front element of the queue (the one being removedis the last element in the array however in britaina line of people is called "queue,and getting into line to wait for service is called "queuing up
20,192
chap listsstacksand queues front rear (afront rear (bfigure after repeated useelements in the array-based queue will drift to the back of the array (athe queue after the initial four numbers and have been inserted (bthe queue after elements and are deletedfollowing which and are inserted enqueue operations will require th(ntimebecause the elements currently in the queue must each be shifted one position in the array if instead we chose the rear element of the queue to be in position then an enqueue operation is equivalent to an append operation on list this requires only th( time but nowa dequeue operation requires th(ntimebecause all of the elements must be shifted down by one position to retain the property that the remaining queue elements reside in the first positions of the array far more efficient implementation can be obtained by relaxing the requirement that all elements of the queue must be in the first positions of the array we will still require that the queue be stored be in contiguous array positionsbut the contents of the queue will be permitted to drift within the arrayas illustrated by figure nowboth the enqueue and the dequeue operations can be performed in th( time because no other elements in the queue need be moved this implementation raises new problem assume that the front element of the queue is initially at position and that elements are added to successively higher-numbered positions in the array when elements are removed from the queuethe front index increases over timethe entire queue will drift toward the higher-numbered positions in the array once an element is inserted into the highest-numbered position in the arraythe queue has run out of space this happens despite the fact that there might be free positions at the low end of the array where elements have previously been removed from the queue the "drifting queueproblem can be solved by pretending that the array is circular and so allow the queue to continue directly from the highest-numbered position in the array to the lowest-numbered position this is easily implemented
20,193
sec queues front front rear ( (brear figure the circular queue with array positions increasing in the clockwise direction (athe queue after the initial four numbers and have been inserted (bthe queue after elements and are deletedfollowing which and are inserted through use of the modulus operator (denoted by in javain this waypositions in the array are numbered from through size- and position size- is defined to immediately precede position (which is equivalent to position size sizefigure illustrates this solution there remains one more seriousthough subtleproblem to the array-based queue implementation how can we recognize when the queue is empty or fullassume that front stores the array index for the front element in the queueand rear stores the array index for the rear element if both front and rear have the same positionthen with this scheme there must be one element in the queue thusan empty queue would be recognized by having rear be one less than front (taking into account the fact that the queue is circularso position size- is actually considered to be one less than position but what if the queue is completely fullin other wordswhat is the situation when queue with array positions available contains elementsin this caseif the front element is in position then the rear element is in position size- but this means that the value for rear is one less than the value for front when the circular nature of the queue is taken into account in other wordsthe full queue is indistinguishable from the empty queueyou might think that the problem is in the assumption about front and rear being defined to store the array indices of the front and rear elementsrespectivelyand that some modification in this definition will allow solution unfortunatelythe problem cannot be remedied by simple change to the definition for front and rearbecause of the number of conditions or states that the queue can be in ignoring the actual position of the first elementand ignoring the actual values of the elements stored in the queuehow many different states are therethere can
20,194
chap listsstacksand queues be no elements in the queueone elementtwoand so on at most there can be elements in the queue if there are array positions this means that there are different states for the queue ( through elements are possibleif the value of front is fixedthen different values for rear are needed to distinguish among the states howeverthere are only possible values for rear unless we invent special case forsayempty queues this is an example of the pigeonhole principle defined in exercise the pigeonhole principle states thatgiven pigeonholes and pigeonswhen all of the pigeons go into the holes we can be sure that at least one hole contains more than one pigeon in similar mannerwe can be sure that two of the states are indistinguishable by their relative values of front and rear we must seek some other way to distinguish full from empty queues one obvious solution is to keep an explicit count of the number of elements in the queueor at least boolean variable that indicates whether the queue is empty or not another solution is to make the array be of size and only allow elements to be stored which of these solutions to adopt is purely matter of the implementor' taste in such affairs my choice is to use an array of size figure shows an array-based queue implementation listarray holds the queue elementsand as usualthe queue constructor allows an optional parameter to set the maximum size of the queue the array as created is actually large enough to hold one element more than the queue will allowso that empty queues can be distinguished from full queues method size is used to control the circular motion of the queue (it is the base for the modulus operatormethod rear is set to the position of the rear element in this implementationthe front of the queue is defined to be toward the lower numbered positions in the array (in the counter-clockwise direction in figure )and the rear is defined to be toward the higher-numbered positions thusenqueue increments the rear pointer (modulus size)and dequeue increments the front pointer implementation of all member functions is straightforward linked queues the linked queue implementation is straightforward adaptation of the linked list figure shows the linked queue class declaration methods front and rear are pointers to the front and rear queue elementsrespectively we will use header link nodewhich allows for simpler implementation of the enqueue operation by avoiding any special cases when the queue is empty on initializationthe front and rear pointers will point to the header nodeand front will always point to the header node while rear points to the true last link node in the queue method
20,195
sec queues /array-based queue implementation class aqueue implements queue private static final int defaultsize private int maxsize/maximum size of queue private int front/index of front element private int rear/index of rear element private [listarray/array holding queue elements /constructors aqueue(this(defaultsize)@suppresswarnings("unchecked"/for generic array aqueue(int sizemaxsize size+ rear front listarray ( [])new object[maxsize]/create listarray public void clear(rear front /reinitialize public void enqueue( it/put "itin queue assert ((rear+ maxsize!front "queue is full"rear (rear+ maxsize/circular increment listarray[rearitpublic dequeue(/take element out of queue assert length(! "queue is empty" it listarray[front]front (front+ maxsize/circular increment return itpublic frontvalue(/get front value assert length(! "queue is empty"return listarray[front]public int length(/return length return ((rear+maxsizefront maxsizefigure an array-based queue implementation
20,196
chap listsstacksand queues /linked queue implementation class lqueue implements queue private link front/pointer to front queue node private link rear/pointer to rear queuenode int size/number of elements in queue /constructors public lqueue(init()public lqueue(int sizeinit()/ignore size private void init(/initialize queue front rear new link(null)size public void clear(init()/reinitialize queue public void enqueue( it/put element on rear rear setnext(new link(itnull))rear rear next()size++public dequeue(/remove element from front assert size ! "queue is empty" it front next(element()/store dequeued value front setnext(front next(next())/advance front if (front next(=nullrear front/last object size--return it/return object public frontvalue(/get front element assert size ! "queue is empty"return front next(element()public int length(return size/return length figure linked queue class implementation
20,197
enqueue places the new element in link node at the end of the linked list ( the node that rear points toand then advances rear to point to the new link node method dequeue grabs the first element of the list removes it comparison of array-based and linked queues all member functions for both the array-based and linked queue implementations require constant time the space comparison issues are the same as for the equivalent stack implementations unlike the array-based stack implementationthere is no convenient way to store two queues in the same arrayunless items are always transferred directly from one queue to the other dictionaries the most common objective of computer programs is to store and retrieve data much of this book is about efficient ways to organize collections of data records so that they can be stored and retrieved quickly in this section we describe simple interface for such collectioncalled dictionary the dictionary adt provides operations for storing recordsfinding recordsand removing records from the collection this adt gives us standard basis for comparing various data structures before we can discuss the interface for dictionarywe must first define the concepts of key and comparable objects if we want to search for given record in databasehow should we describe what we are looking fora database record could simply be numberor it could be quite complicatedsuch as payroll record with many fields of varying types we do not want to describe what we are looking for by detailing and matching the entire contents of the record if we knew everything about the record alreadywe probably would not need to look for it insteadwe typically define what record we want in terms of key value for exampleif searching for payroll recordswe might wish to search for the record that matches particular id number in this example the id number is the search key to implement the search functionwe require that keys be comparable at minimumwe must be able to take two keys and reliably determine whether they are equal or not that is enough to enable sequential search through database of records and find one that matches given key howeverwe typically would like for the keys to define total order (see section )which means that we can tell which of two keys is greater than the other using key types with total orderings gives the database implementor the opportunity to organize collection of records in way that makes searching more efficient an example is storing the
20,198
chap listsstacksand queues /*the dictionary abstract class *public interface dictionary /*reinitialize dictionary *public void clear()/*insert record @param the key for the record being inserted @param the record being inserted *public void insert(key ke )/*remove and return record @param the key of the record to be removed @return maching record if multiple records match " "remove an arbitrary one return null if no record with key "kexists *public remove(key )/*remove and return an arbitrary record from dictionary @return the record removedor null if none exists *public removeany()/*@return record matching " (null if none existsif multiple records matchreturn an arbitrary one @param the key of the record to find *public find(key )/*@return the number of records in the dictionary *public int size()}figure the adt for simple dictionary records in sorted order in an arraywhich permits binary search fortunatelyin practice most fields of most records consist of simple data types with natural total orders for exampleintegersfloatsdoublesand character strings all are totally ordered ordering fields that are naturally multi-dimensionalsuch as point in two or three dimensionspresent special opportunities if we wish to take advantage of their multidimensional nature this problem is addressed in section figure shows the definition for simple abstract dictionary class the methods insert and find are the heart of the class method insert takes record and inserts it into the dictionary method find takes key value and returns some record from the dictionary whose key matches the one provided if there are multiple records in the dictionary with that key valuethere is no requirement as to which one is returned
20,199
method clear simply re-initializes the dictionary the remove method is similar to findexcept that it also deletes the record returned from the dictionary once againif there are multiple records in the dictionary that match the desired keythere is no requirement as to which one actually is removed and returned method size returns the number of elements in the dictionary the remaining method is removeany this is similar to removeexcept that it does not take key value insteadit removes an arbitrary record from the dictionaryif one exists the purpose of this method is to allow user the ability to iterate over all elements in the dictionary (of coursethe dictionary will become empty in the processwithout the removeany methoda dictionary user could not get at record of the dictionary that he didn' already know the key value for with the removeany methodthe user can process all records in the dictionary as shown in the following code fragment while (dict size( it dict removeany()dosomething(it)there are other approaches that might seem more natural for iterating though dictionarysuch as using "firstand "nextfunction but not all data structures that we want to use to implement dictionary are able to do "firstefficiently for examplea hash table implementation cannot efficiently locate the record in the table with the smallest key value by using removeanywe have mechanism that provides generic access given database storing records of particular typewe might want to search for records in multiple ways for examplewe might want to store payroll records in one dictionary that allows us to search by idand also store those same records in second dictionary that allows us to search by name figure shows the definition for payroll record the payroll class has multiple fieldseach of which might be used as search key simply by varying the type for the keyand looking at the appropriate field in each recordwe can define dictionary whose search key is the id fieldanother whose search key is the name fieldand third whose search key is the address field of the payroll class figure shows an example where payroll objects are stored in two separate dictionariesone using the id field as the key and the other using the name field as the key the fundamental operation for dictionary is finding record that matches given key this raises the issue of how to extract the key from record we would like any given dictionary implementation to support arbitrary record typesso we