id
int64
0
25.6k
text
stringlengths
0
4.59k
20,800
only one iteration of the inner loop for each iteration of the outer loop thusin this casewe perform minimum number of comparisons of coursewe might have to do lot more work than this if the input array is extremely out of order in factwe will have to do the most work if the input array is in decreasing order java util methods for arrays and random numbers because arrays are so importantjava provides number of built-in methods for performing common tasks on arrays these methods appear as static methods in the java util arrays class that isthey are associated with the classjava util arrays itselfand not with particular instance of this class describing some of these methods will have to waithoweveruntil later in this book (when we discuss the concept that these methods are based onsome simple methods of java util arrays we list below some simple methods of class java util arrays that need no further explanationequals(ab)returns true if and only if the array and the array are equal two arrays are considered equal if they have the same number of elements and every corresponding pair of elements in the two arrays are equal that isa and have the same elements in the same order fill( , )stores element into every cell of array sort( )sorts the array using the natural ordering of its elements tostring( )returns string representation of the array for examplethe following string would be returned by the method tostring called on an array of integers [ , , , , , , ][ note thatfrom the list abovejava has built-in sorting algorithm this is not the insertion-sort algorithm we presented abovehowever it is an algorithm called quick-sortwhich usually runs much faster than insertion--sort we discuss the quick-sort algorithm in section an example using pseudo-random numbers
20,801
methods above code fragment test program arraytest that uses various built-in methods of the arrays class program arraytest uses another feature in java--the ability to generate pseudorandomnumbersthat isnumbers that are statistically random (but not truly randomin particularit uses java util random objectwhich is pseudo-random number generatorthat isan object that computesor "generates, sequence of numbers that are statistically random such generator needs place to starthowever,which is its seed the sequence of numbers generated for given seed will always be the same in our programwe set the seed to the current time in milliseconds since january (using the method system currenttimemillis)which will be different each time we run our program once we have set the seedwe can repeatedly get random number between and by calling the nextint method with argument we show sample output of this program belowarrays equal before sorttrue arrays equal after sortfalse old [ , , , , , , , , ,
20,802
by the waythere is slight chance that the old and num arrays will remain equal even after num is sortednamelyif num is already sorted before it is cloned but the odds of this occurring are less than one in four million simple cryptography with strings and character arrays one of the primary applications of arrays is the representation of strings of characters that isstring objects are usually stored internally as an array of characters even if strings may be represented in some other waythere is natural relationship between strings and character arrays--both use indices to refer to their characters because of this relationshipjava makes it easy for us to create string objects from character arrays and vice versa specificallyto create an object of class string from character array awe simply use the expressionnew string(athat isone of the constructors for the string class takes character array as its argument and returns string having the same characters in the same order as the array for examplethe string we would construct from the array [acatis acat likewisegiven string swe can create character array representation of by using the expressions tochararray(that isthe string class has methodtochararraywhich returns an array (of type char[]with the same characters as for exampleif we call tochararray on the string adogwe would get the array [adogthe caesar cipher one area where being able to switch from string to character array and back again is useful is in cryptographythe science of secret messages and their applications this field studies ways of performing encryptionwhich takes messagecalled the plaintextand converts it into scrambled messagecalled the ciphertext likewisecryptography also studies corresponding ways of performing decryptionwhich takes ciphertext and turns it back into its original plaintext arguably the earliest encryption scheme is the caesar cipherwhich is named after julius caesarwho used this scheme to protect important military messages (all of caesar' messages were written in latinof coursewhich already makes them unreadable for most of us!the caesar cipher is simple way to obscure message written in language that forms words with an alphabet
20,803
is three letters after it in the alphabet for that language soin an english messagewe would replace each with deach with eeach with fand so on we continue this approach all the way up to wwhich is replaced with thenwe let the substitution pattern wrap aroundso that we replace with ay with band with using characters as array indices if we were to number our letters like array indicesso that is is is and so onthen we can write the caesar cipher as simple formulareplace each letter with the letter ( mod where mod is the modulus operatorwhich returns the remainder after performing an integer division this operator is denoted %in javaand it is exactly the operator we need to easily perform the wrap around at the end of the alphabet for mod is mod is and mod is the decryption algorithm for the caesar cipher is just the opposite--we replace each letter with the one three places before itwith wrap around for aband we can capture this replacement rule using arrays for encryption and decryption since every character in java is actually stored as number--its unicode value-we can use letters as array indices for an uppercase character cfor examplewe can use as an array index by taking the unicode value for and subtracting of coursethis only works for uppercase lettersso we will require our secret messages to be uppercase we can then use an arrayencryptthat represents the encryption replacement ruleso that encrypt [iis the letter that replaces letter number (which is - for an uppercase character in unicodethis usage is illustrated in figure likewisean arraydecryptcan represent the decryption replacement ruleso that decrypt[iis the letter that replaces letter number figure illustrating the use of uppercase characters as array indicesin this case to perform the replacement rule for caesar cipher encryption
20,804
caesar cipherwhich uses the approach above and also makes use of conversions between strings and character arrays when we run this program (to perform simple test)we get the following outputencryption order defghijklmnopqrstuvwxyzabc decryption order xyzabcdefghijklmnopqrstuvw wkh hdjoh lv lq sodbphhw dw mrh' the eagle is in playmeet at joe' code fragment for the caesar cipher simplecomplete java class
20,805
20,806
conflict gamesuse two-dimensional "board programs that deal with such positional games need way of representing objects in two-dimensional space natural way to do this is with two-dimensional arraywhere we use two indicessay and jto refer to the cells in the array the first index usually refers to row number and the second to column number given such an array we can then maintain two-dimensional game boardsas well as perform other kinds of computations involving data that is stored in rows and columns arrays in java are one-dimensionalwe use single index to access each cell of an array neverthelessthere is way we can define two-dimensional arrays in java-we can create two-dimensional array as an array of arrays that iswe can define two--dimensional array to be an array with each of its cells being another array such two--dimensional array is sometimes also called matrix in javawe declare two--dimensional array as followsint[][ new int[ ][ ]this statement creates two-dimensional "array of arrays,ywhich is having rows and columns that isy is an array of length such that each element of is an array of length of integers (see figure the following would then be valid uses of array and int variables and jy[ ][ + [ ][ lengthj [ lengthtwo-dimensional arrays have many applications to numerical analysis rather than going into the details of such applicationshoweverwe explore an application of two-dimensional arrays for implementing simple positional game figure illustration of two-dimensional integer arrayywhich has rows and columns the value of [ ][ is and the value of [ ][ is
20,807
as most school children knowtic-tac-toe is game played in three-by-three board two players-- and --alternate in placing their respective marks in the cells of this boardstarting with player if either player succeeds in getting three of his or her marks in rowcolumnor diagonalthen that player wins this is admittedly not sophisticated positional gameand it' not even that much fun to playsince good player can always force tie tic-tac-toe' saving grace is that it is nicesimple example showing how two-dimensional arrays can be used for positional games software for more sophisticated positional gamessuch as checkerschessor the popular simulation gamesare all based on the same approach we illustrate here for using two-dimensional array for tic--tac-toe (see exercise - the basic idea is to use two-dimensional arrayboardto maintain the game board cells in this array store values that indicate if that cell is empty or stores an or that isboard is three-by-three matrixwhose middle row consists of the cells board[ ][ ]board[ ][ ]and board[ ][ in our casewe choose to make the cells in the board array be integerswith indicating an empty cella indicating an xand - indicating this encoding allows us to have simple way of testing if given board configuration is win for or onamelyif the values of rowcolumnor diagonal add up to - or we illustrate this approach in figure figure an illustration of tic-tac-toe board and the two-dimensional integer arrayboardrepresenting it
20,808
players in code fragments and we show sample output in figure note that this code is just for maintaining the tic-tac-toe board and registering movesit doesn' perform any strategy or allow someone to play tic-tac-toe against the computer such program would make good project in class on artificial intelligence code fragment simplecomplete java class for playing tic-tac-toe between two players (continues in code fragment
20,809
for playing tic-tac-toe between two players (continued from code fragment
20,810
sample output of tic-tac-toe game singly linked lists in the previous sectionswe presented the array data structure and discussed some of its applications arrays are nice and simple for storing things in certain orderbut they have the drawback of not being very adaptablesince we have to fix the size of the array in advance there are other ways to store sequence of elementshoweverthat do not have this drawback in this sectionwe explore an important alternate implementationwhich is known as the singly linked list linked listin its simplest formis collection of nodes that together form linear ordering the ordering is determined as in the children' game "follow the leader,in that each node is an object that stores reference to an element and referencecalled nextto another node (see figure figure example of singly linked list whose elements are strings indicating airport codes the next pointers of each node are shown as arrows the null object is denoted as it might seem strange to have node reference another nodebut such scheme easily works the next reference inside node can be viewed as link or pointer to another node likewisemoving from one node to another by following next reference is known as link hopping or pointer hopping the first and last node of linked list usually are called the head and tail of the listrespectively thuswe can link hop through the list starting at the head and ending at the tail we can identify the tail as the node having null next referencewhich indicates the end of the list linked list defined in this way is known as singly linked list
20,811
determined by the chain of next links going from each node to its successor in the list unlike an arraya singly linked list does not have predetermined fixed sizeand uses space proportional to the number of its elements likewisewe do not keep track of any index numbers for the nodes in linked list so we cannot tell just by examining node if it is the secondfifthor twentieth node in the list implementing singly linked list to implement singly linked listwe define node classas shown in code fragment which specifies the type of objects stored at the nodes of the list here we assume elements are character strings in we describe how to define nodes that can store arbitrary types of elements given the node classwe can define classslinkedlistshown in code fragment defining the actual linked list this class keeps reference to the head node and variable counting the total number of nodes code fragment singly linked list implementation of node of code fragment partial implementation of the class for singly linked list
20,812
when using singly linked listwe can easily insert an element at the head of the listas shown in figure and code fragment the main idea is that we create new nodeset its next link to refer to the same object as headand then set head to point to the new node figure insertion of an element at the head of singly linked list(abefore the insertion(bcreation of new node(cafter the insertion
20,813
inserting new node at the beginning of singly linked list note that this method works even if the list is empty note that we set the next pointer for the new node before we make variable head point to inserting an element at the tail of singly linked list we can also easily insert an element at the tail of the listprovided we keep reference to the tail nodeas shown in figure in this casewe create new nodeassign its next reference to point to the null objectset the next reference of the tail to point to this new objectand then assign the tail reference itself to this new node we give the details in code fragment
20,814
(abefore the insertion(bcreation of new node(cafter the insertion note that we set the next link for the tail in (bbefore we assign the tail variable to point to the new node in (ccode fragment inserting new node at the end of singly linked list this method works also if the list is empty note that we set the next pointer for the old tail node before we make variable tail point to the new node removing an element in singly linked list
20,815
remove an element at the head this operation is illustrated in figure and given in detail in code fragment figure removal of an element at the head of singly linked list(abefore the removal( "linking outthe old new node(cafter the removal code fragment removing the node at the beginning of singly linked list unfortunatelywe cannot easily delete the tail node of singly linked list even if we have tail reference directly to the last node of the listwe must be able to access the node before the last node in order to remove the last node but we cannot reach the node before the tail by following next links from the tail the only way to
20,816
the list but such sequence of link hopping operations could take long time doubly linked lists as we saw in the previous sectionremoving an element at the tail of singly linked list is not easy indeedit is time consuming to remove any node other than the head in singly linked listsince we do not have quick way of accessing the node in front of the one we want to remove indeedthere are many applications where we do not have quick access to such predecessor node for such applicationsit would be nice to have way of going both directions in linked list there is type of linked list that allows us to go in both directions--forward and reverse--in linked list it is the doubly linked list such lists allow for great variety of quick update operationsincluding insertion and removal at both endsand in the middle node in doubly linked list stores two references-- next linkwhich points to the next node in the listand prev linkwhich points to the previous node in the list java implementation of node of doubly linked list is shown in code fragment where we assume that elements are character strings in we discuss how to define nodes for arbitrary element types code fragment java class dnode representing node of doubly linked list that stores character string
20,817
to simplify programmingit is convenient to add special nodes at both ends of doubly linked lista header node just before the head of the listand trailer node just after the tail of the list these "dummyor sentinel nodes do not store any elements the header has valid next reference but null prev referencewhile the trailer has valid prev reference but null next reference doubly linked list with these sentinels is shown in figure note that linked list object would simply need to store references to these two sentinels and size counter that keeps track of the number of elements (not counting sentinelsin the list figure doubly linked list with sentinelsheader and trailermarking the ends of the list an empty list would have these sentinels pointing to each other we do not show the null prev pointer for the
20,818
trailer inserting or removing elements at either end of doubly linked list is straightforward to do indeedthe prev links eliminate the need to traverse the list to get to the node just before the tail we show the removal at the tail of doubly linked list in figure and the details for this operation in code fragment figure removing the node at the end of doubly linked list with header and trailer sentinels(abefore deleting at the tail(bdeleting at the tail(cafter the deletion code fragment removing the last node of doubly linked list variable size keeps track of the current number of elements in the list note that this method works also if the list has size one
20,819
doubly linked listas shown in figure and code fragment figure adding an element at the front(aduring(bafter code fragment inserting new node at the beginning of doubly linked list variable size keeps track of the current number of elements in the list note that this method works also on an empty list
20,820
doubly linked lists are useful for more than just inserting and removing elements at the head and tail of the listhowever they also are convenient for maintaining list of elements while allowing for insertion and removal in the middle of the list given node of doubly linked list (which could be possibly the header but not the trailer)we can easily insert new node immediately after specificallylet the be node following we execute the following steps make ' prev link refer to make ' next link refer to make ' prev link refer to make ' next link refer to this method is given in detail in code fragment and is illustrated in figure recalling our use of header and trailer sentinelsnote that this algorithm works even if is the tail node (the node just before the trailercode fragment inserting new node after given node in doubly linked list
20,821
storing jfk(acreating new node with element bwi and linking it in(bafter the insertion removal in the middle of doubly linked list likewiseit is easy to remove node in the middle of doubly linked list we access the nodes and on either side of using ' getprev and getnext methods (these nodes must existsince we are using sentinelsto remove node vwe simply have and point to each other instead of to we refer to this operation as the linking out of we also null out ' prev and next pointers so as not to retain old references into the list this algorithm is given in code fragment and is illustrated in figure code fragment removing node in doubly linked list this method works even if is the firstlastor only nonsentinel node
20,822
before the removal(blinking out the old node(cafter the removal (and garbage collectionan implementation of doubly linked list in code fragments we show an implementation of doubly linked list with nodes that store character string elements code fragment java class dlist for doubly linked list whose nodes are objects of class dnode (see code fragment storing character strings (continues in code fragment
20,823
java class dlist for doubly linked list (continues in code fragment
20,824
doubly linked list class (continued from code fragment
20,825
object of class dnodewhich store string elementsare used for all the nodes of the listincluding the header and trailer sentinels we can use class dlist for doubly linked list of string objects only to build linked list of other types of objectswe can use generic declarationwhich we discuss in methods getfirst and getlast provide direct access to the first and last nodes in the list methods getprev and getnext allow to traverse the list methods hasprev and hasnext detect the boundaries of the list methodsaddfirst and addlast add new node at the beginning or end of the list methodsadd before and add after add new node before or after an existing node
20,826
having only single removal methodremoveis not actually restrictionsince we can remove at the beginning or end of doubly linked list by executing remove( getfirst()or remove( getlast())respectively method tostring for converting an entire list into string is useful for testing and debugging purposes circularly linked lists and linked-list sorting in this sectionwe study some applications and extensions of linked lists circularly linked lists and duckduckgoose the children' game"duckduckgoose,is played in many cultures children in minnesota play version called "duckduckgrey duck(but please don' ask us why in indianathis game is called "the mosh pot and children in the czech republic and ghana play sing-song versions known respectively as "pesekand "antoakyire variation on the singly linked listcalled the circularly linked listis used for number of applications involving circle gameslike "duckduckgoose we discuss this type of list and the circle-game application next circularly linked list has the same kind of nodes as singly linked list that iseach node in circularly linked list has next pointer and reference to an element but there is no head or tail in circularly linked list for instead of having the last node' next pointer be nullin circularly linked listit points back to the first node thusthere is no first or last node if we traverse the nodes of circularly linked list from any node by following next pointerswe will cycle through the nodes even though circularly linked list has no beginning or endwe nevertheless need some node to be marked as special nodewhich we call the cursor the cursor node allows us to have place to start from if we ever need to traverse circularly linked list and if we remember this starting pointthen we can also know when we are done-we are done with traversal of circularly linked list when we return to the node that was the cursor node when we started we can then define some simple update methods for circularly linked listadd( )insert new node immediately after the cursorif the list is emptythen becomes the cursor and its next pointer points to itself remove()remove and return the node immediately after the cursor (not the cursor itselfunless it is the only node)if the list becomes emptythe cursor is set to null
20,827
in code fragment we show java implementation of circularly linked listwhich uses the node class from code fragment and includes also tostring method for producing string representation of the list code fragment with simple nodes circularly linked list class
20,828
there are few observations we can make about the circlelist class it is simple program that can provide enough functionality to simulate circle gameslike duckduckgooseas we will soon show it is not robust programhowever in particularif circle list is emptythen calling advance or remove on that list will cause an exception (which one?exercise - deals with this exception-generating behavior and ways of handling this empty-list condition better duckduckgoose in the children' gameduckduckgoosea group of children sit in circle one of them is elected "itand that person walks around the outside of the circle the person who is "itpats each child on the headsaying "duckeach timeuntil reaching child that the "itperson identifies as "goose at this point there is mad scrambleas the "gooseand the "itperson race around the circle who ever returns to the goose' former place first gets to remain in the circle the loser of this race is the "itperson for the next round of play this game continues like this until the children get bored or an adult tells them it is snack timeat which point the game ends (see figure figure the duckduckgoose game(achoosing the "goose;(bthe race to the "goose'splace between the "gooseand the "itperson simulating this game is an ideal application of circularly linked list the children can represent nodes in the list the "itperson can be identified as the person sitting after the cursorand can be removed from the circle to simulate the marching around we can advance the cursor with each "duckthe "itperson identifieswhich we can simulate with random decision once "gooseis
20,829
simulate whether the "gooseor the "itperson win the raceand insert the winner back into the list we can then advance the cursor and insert the "itperson back in to repeat the process (or be done if this is the last time we play the gameusing circularly linked list to simulate duckduckgoose we give java code for simulation of duckduckgoose in code fragment code fragment the main method from program that uses circularly linked list to simulate the duckduckgoose children' game
20,830
20,831
figure figure sample output from the duckduckgoose program note that each iteration in this particular execution of this program produces different outcomedue to the different initial configurations and the use of random choices to identify ducks and geese likewisewhether the "duckor the "goosewins the race is also differentdepending on random choices this execution shows situation where the next child after the "itperson is immediately identified as the "goose,as well situation where the "itperson walks all the way around the group of children before identifying the "goose such situations also illustrate the usefulness of using circularly linked list to simulate circular games like duckduckgoose sorting linked list
20,832
doubly linked list java implementation is given in code fragment code fragment high-level pseudo-code description of insertion-sort on doubly linked list code fragment java implementation of the insertion-sort algorithm on doubly linked list represented by class dlist (see code fragments
20,833
recursion we have seen that repetition can be achieved by writing loopssuch as for loops and while loops another way to achieve repetition is through recursionwhich occurs when function calls itself we have seen examples of methods calling other methodsso it should come as no surprise that most modern programming languagesincluding javaallow method to call itself in this sectionwe will see why this capability provides an elegant and powerful alternative for performing repetitive tasks the factorial function to illustrate recursionlet us begin with simple example of computing the value of the factorial function the factorial of positive integer ndenoted !is defined as the product of the integers from to if then nis defined as by convention more formallyfor any integer > for example * * * * to make the connection with methods clearerwe use the notation factorial(nto denote
20,834
formulation to see thisobserve that factorial( ( factorial( thuswe can define factorial( in terms of factorial( in generalfor positive integer nwe can define factorial(nto be *factorial( this leads to the following recursive definition this definition is typical of many recursive definitions firstit contains one or more base caseswhich are defined nonrecursively in terms of fixed quantities in this casen is the base case it also contains one or more recursive caseswhich are defined by appealing to the definition of the function being defined observe that there is no circularity in this definitionbecause each time the function is invokedits argument is smaller by one recursive implementation of the factorial function let us consider java implementation of the factorial function shown in code fragment under the name recursivefactorial(notice that no looping was needed here the repeated recursive invocations of the function takes the place of looping code fragment the factorial function recursive implementation of we can illustrate the execution of recursive function definition by means of recursion trace each entry of the trace corresponds to recursive call each new recursive function call is indicated by an arrow to the newly called function when the function returnsan arrow showing this return is drawn and the return value may be indicated with this arrow an example of trace is shown in figure what is the advantage of using recursionalthough the recursive implementation of the factorial function is somewhat simpler than the iterative versionin this case there is no compelling reason for preferring recursion over iteration for some
20,835
easier to understand than an iterative implementation such an example follows figure recursion trace for the call recursivefactorial( drawing an english ruler as more complex example of the use of recursionconsider how to draw the markings of typical english ruler ruler is broken up into -inch intervalsand each interval consists of set of ticks placed at intervals of / inch / inchand so on as the size of the interval decreases by halfthe tick length decreases by one (see figure figure three sample outputs of the rulerdrawing function(aa -inch ruler with major tick length (ba -inch ruler with major tick length (ca -inch ruler with major tick length
20,836
the major tick length we will not worry about actual distanceshoweverand just print one tick per line recursive approach to ruler drawing our approach to drawing such ruler consists of three functions the main function drawruler(draws the entire ruler its arguments are the total number of inches in the rulerninchesand the major tick lengthmajorlength the utility function drawonetick(draws single tick of the given length it can also be given an optional integer labelwhich is printed if it is nonnegative the interesting work is done by the recursive function drawticks()which draws the sequence of ticks within some interval its only argument is the tick length associated with the interval' central tick consider the -inch ruler with major tick length shown in figure (bignoring the lines containing and let us consider how to draw the sequence of ticks lying between these lines the central tick (at / inchhas length observe that the two patterns of ticks above and below this central tick are identicaland each has central tick of length in generalan interval with central tick length > is composed of the followingan interval with central tick length
20,837
single tick of length interval with central tick length with each recursive callthe length decreases by one when the length drops to zerowe simply return as resultthis recursive process will always terminate this suggests recursive processin which the first and last steps are performed by calling the drawticks( recursively the middle step is performed by calling the function drawonetick(lthis recursive formulation is shown in code fragment as in the factorial examplethe code has base case (when in this instance we make two recursive calls to the function code fragment recursive implementation of function that draws ruler illustrating ruler drawing using recursion trace the recursive execution of the recursive drawticks functiondefined abovecan be visualized using recursion trace
20,838
howeverbecause each instance makes two recursive calls to illustrate thiswe will show the recursion trace in form that is reminiscent of an outline for document see figure figure partial recursion trace for the call drawticks( the second pattern of calls for drawticks( is not shownbut it is identical to the first throughout this book we shall see many other examples of how recursion can be used in the design of data structures and algorithms
20,839
as we discussed aboverecursion is the concept of defining method that makes call to itself whenever method calls itselfwe refer to this as recursive call we also consider method to be recursive if it calls another method that ultimately leads to call back to the main benefit of recursive approach to algorithm design is that it allows us to take advantage of the repetitive structure present in many problems by making our algorithm description exploit this repetitive structure in recursive waywe can often avoid complex case analyses and nested loops this approach can lead to more readable algorithm descriptionswhile still being quite efficient in additionrecursion is useful way for defining objects that have repeated similar structural formsuch as in the following examples example modern operating systems define file-system directories (which are also sometimes called "folders"in recursive way namelya file system consists of top-level directoryand the contents of this directory consists of files and other directorieswhich in turn can contain files and other directoriesand so on the base directories in the file system contain only filesbut by using this recursive definitionthe operating system allows for directories to be nested arbitrarily deep (as long as there is enough space in memoryexample much of the syntax in modern programming languages is defined in recursive way for examplewe can define an argument list in java using the following notationargument-listargument argument-listargument in other wordsan argument list consists of either (ian argument or (iian argument list followed by comma and an argument that isan argument list consists of comma-separated list of arguments similarlyarithmetic expressions can be defined recursively in terms of primitives (like variables and constantsand arithmetic expressions example there are many examples of recursion in art and nature one of the most classic examples of recursion used in art is in the russian matryoshka dolls each doll is made of solid wood or is hollow and contains another matryoshka doll inside it linear recursion
20,840
that it makes at most one recursive call each time it is invoked this type of recursion is useful when we view an algorithmic problem in terms of first or last element plus remaining set that has the same structure as the original set summing the elements of an array recursively supposefor examplewe are given an arrayaof integers that we wish to sum together we can solve this summation problem using linear recursion by observing that the sum of all integers in is equal to [ ]if or the sum of the first integers in plus the last element in in particularwe can solve this summation problem using the recursive algorithm described in code fragment code fragment summing the elements in an array using linear recursion this example also illustrates an important property that recursive method should always possess--the method terminates we ensure this by writing nonrecursive statement for the case in additionwe always perform the recursive call on smaller value of the parameter ( than that which we are given ( )so thatat some point (at the "bottomof the recursion)we will perform the nonrecursive part of the computation (returning [ ]in generalan algorithm that uses linear recursion typically has the following formtest for base cases we begin by testing for set of base cases (there should be at least onethese base cases should be defined so that every possible chain of recursive calls will eventually reach base caseand the handling of each base case should not use recursion recur after testing for base caseswe then perform single recursive call this recursive step may involve test that decides which of several possible recursive calls to makebut it should ultimately choose to make just one of these calls each time we perform this step moreoverwe should define each possible recursive call so that it makes progress towards base case
20,841
we can analyze recursive algorithm by using visual tool known as recursion trace we used recursion tracesfor exampleto analyze and visualize the recursive fibonacci function of section and we will similarly use recursion traces for the recursive sorting algorithms of sections and to draw recursion tracewe create box for each instance of the method and label it with the parameters of the method alsowe visualize recursive call by drawing an arrow from the box of the calling method to the box of the called method for examplewe illustrate the recursion trace of the linearsum algorithm of code fragment in figure we label each box in this trace with the parameters used to make this call each time we make recursive callwe draw line to the box representing the recursive call we can also use this diagram to visualize stepping through the algorithmsince it proceeds by going from the call for to the call for to the call for and so onall the way down to the call for when the final call finishesit returns its value back to the call for which adds in its valueand returns this partial sum to the call for and so onuntil the call for returns its partial sum to the call for figure recursion trace for an execution of linearsum( ,nwith input parameters { , , , , and from figure it should be clear that for an input array of size nalgorithm linearsum makes calls henceit will take an amount of time that is roughly proportional to nsince it spends constant amount of time performing the
20,842
used by the algorithm (in addition to the array ais also roughly proportional to nsince we need constant amount of memory space for each of the boxes in the trace at the time we make the final recursive call (for reversing an array by recursion nextlet us consider the problem of reversing the elements of an arrayaso that the first element becomes the lastthe second element becomes second to the lastand so on we can solve this problem using linear recursionby observing that the reversal of an array can be achieved by swapping the first and last elements and then recursively reversing the remaining elements in the array we describe the details of this algorithm in code fragment using the convention that the first time we call this algorithm we do so as reversearray( , , code fragment reversing the elements of an array using linear recursion note thatin this algorithmwe actually have two base casesnamelywhen and when moreoverin either casewe simply terminate the algorithmsince sequence with zero elements or one element is trivially equal to its reversal furthermorenote that in the recursive step we are guaranteed to make progress towards one of these two base cases if is oddwe will eventually reach the caseand if is evenwe will eventually reach the case the above argument immediately implies that the recursive algorithm of code fragment is guaranteed to terminate defining problems in ways that facilitate recursion to design recursive algorithm for given problemit is useful to think of the different ways we can subdivide this problem to define problems that have the same general structure as the original problem this process sometimes means we need to redefine the original problem to facilitate similar-looking subproblems for examplewith the reversearray algorithmwe added the parameters and so that recursive call to reverse the inner part of the array would have the same structure (and same syntaxas the call to reverse all of thenrather than
20,843
reversearray( , , - in generalif one has difficulty finding the repetitive structure needed to design recursive algorithmit is sometimes useful to work out the problem on few concrete examples to see how the subproblems should be defined tail recursion using recursion can often be useful tool for designing algorithms that have elegantshort definitions but this usefulness does come at modest cost when we use recursive algorithm to solve problemwe have to use some of the memory locations in our computer to keep track of the state of each active recursive call when computer memory is at premiumthenit is useful in some cases to be able to derive nonrecursive algorithms from recursive ones we can use the stack data structurediscussed in section to convert recursive algorithm into nonrecursive algorithmbut there are some instances when we can do this conversion more easily and efficiently specificallywe can easily convert algorithms that use tail recursion an algorithm uses tail recursion if it uses linear recursion and the algorithm makes recursive call as its very last operation for examplethe algorithm of code fragment uses tail recursion to reverse the elements of an array it is not enough that the last statement in the method definition include recursive callhowever in order for method to use tail recursionthe recursive call must be absolutely the last thing the method does (unless we are in base caseof coursefor examplethe algorithm of code fragment does not use tail recursioneven though its last statement includes recursive call this recursive call is not actually the last thing the method does after it receives the value returned from the recursive callit adds this value to [ and returns this sum that isthe last thing this algorithm does is an addnot recursive call when an algorithm uses tail recursionwe can convert the recursive algorithm into nonrecursive oneby iterating through the recursive calls rather than calling them explicitly we illustrate this type of conversion by revisiting the problem of reversing the elements of an array in code fragment we give nonrecursive algorithm that performs this task by iterating through the recursive calls of the algorithm of code fragment we initially call this algorithm as iterativereversearray ( , code fragment reversing the elements of an array using iteration
20,844
when an algorithm makes two recursive callswe say that it uses binary recursion these calls canfor examplebe used to solve two similar halves of some problemas we did in section for drawing an english ruler as another application of binary recursionlet us revisit the problem of summing the elements of an integer array in this casewe can sum the elements in by(irecursively summing the elements in the first half of (iirecursively summing the elements in the second half of aand (iiiadding these two values together we give the details in the algorithm of code fragment which we initially call as binarysum( , ,ncode fragment summing the elements in an array using binary recursion to analyze algorithm binarysumwe considerfor simplicitythe case where is power of two the general case of arbitrary is considered in exercise - figure shows the recursion trace of an execution of method binarysum( , we label each box with the values of parameters and nwhich represent the starting index and length of the sequence of elements to be reversedrespectively notice that the arrows in the trace go from box labeled ( ,nto another box labeled ( , / or ( / , / that isthe value of parameter is halved at each recursive call thusthe depth of the recursionthat isthe maximum number of method instances that are active at the same timeis log thusalgorithm binarysum uses an amount of additional space roughly proportional to this value this is big improvement over the space needed by the linearsum method of code fragment the running time of algorithm binarysum is still roughly
20,845
through our algorithm and there are boxes figure recursion trace for the execution of binarysum( , computing fibonacci numbers via binary recursion let us consider the problem of computing the kth fibonacci number recall from section that the fibonacci numbers are recursively defined as followsf - - for by directly applying this definitionalgorithm binaryfibshown in code fragment computes the sequence of fibonacci numbers using binary recursion code fragment computing the kth fibonacci number using binary recursion
20,846
using this technique is inefficient in this case in factit takes an exponential number of calls to compute the kth fibonacci number in this way specificallylet denote the number of calls performed in the execution of binaryfib(kthenwe have the following values for the 'sn if we follow the pattern forwardwe see that the number of calls more than doubles for each two consecutive indices that isn is more than twice is more than twice is more than twice and so on thusn / which means that binaryfib(kmakes number of calls that are exponential in in other wordsusing binary recursion to compute fibonacci numbers is very inefficient computing fibonacci numbers via linear recursion the main problem with the approach abovebased on binary recursionis that the computation of fibonacci numbers is really linearly recursive problem it is not good candidate for using binary recursion we simply got tempted into using binary recursion because of the way the kth fibonacci numberf depends on the two previous valuesf - and - but we can compute much more efficiently using linear recursion in order to use linear recursionhoweverwe need to slightly redefine the problem one way to accomplish this conversion is to define recursive function that computes pair of consecutive fibonacci numbers ( , - using the convention - then we can use the linearly recursive algorithm shown in code fragment
20,847
number using linear recursion the algorithm given in code fragment shows that using linear recursion to compute fibonacci numbers is much more efficient than using binary recursion since each recursive call to linearfibonacci decreases the argument by the original call linearfibonacci(kresults in series of additional calls that iscomputing the kth fibonacci number via linear recursion requires method calls this performance is significantly faster than the exponential time needed by the algorithm based on binary recursionwhich was given in code fragment thereforewhen using binary recursionwe should first try to fully partition the problem in two (as we did for summing the elements of an arrayorwe should be sure that overlapping recursive calls are really necessary usuallywe can eliminate overlapping recursive calls by using more memory to keep track of previous values in factthis approach is central part of technique called dynamic programmingwhich is related to recursion and is discussed in section multiple recursion generalizing from binary recursionwe use multiple recursion when method may make multiple recursive callswith that number potentially being more than two one of the most common applications of this type of recursion is used when we wish to enumerate various configurations in order to solve combinatorial puzzle for examplethe following are all instances of summation puzzlespot pan bib dog cat pig boy girl baby
20,848
letter in the equationin order to make the equation true typicallywe solve such puzzle by using our human observations of the particular puzzle we are trying to solve to eliminate configurations (that ispossible partial assignments of digits to lettersuntil we can work though the feasible configurations lefttesting for the correctness of each one if the number of possible configurations is not too largehoweverwe can use computer to simply enumerate all the possibilities and test each onewithout employing any human observations in additionsuch an algorithm can use multiple recursion to work through the configurations in systematic way we show pseudocode for such an algorithm in code fragment to keep the description general enough to be used with other puzzlesthe algorithm enumerates and tests all -length sequences without repetitions of the elements of given set we build the sequences of elements by the following steps recursively generating the sequences of elements appending to each such sequence an element not already contained in it throughout the execution of the algorithmwe use the set to keep track of the elements not contained in the current sequenceso that an element has not been used yet if and only if is in another way to look at the algorithm of code fragment is that it enumerates every possible size- ordered subset of uand tests each subset for being possible solution to our puzzle for summation puzzlesu { , , , , , , , , , and each position in the sequence corresponds to given letter for examplethe first position could stand for bthe second for othe third for yand so on code fragment solving combinatorial puzzle by enumerating and testing all possible configurations
20,849
where is empty and { , ,cduring the executionall the permutations of the three characters are generated and tested note that the initial call makes three recursive callseach of which in turn makes two more if we had executed puzzlesolve( ,suon set consisting of four elementsthe initial call would have made four recursive callseach of which would have trace looking like the one in figure figure recursion trace for an execution of puzzlesolve( , , )where is empty and {abcthis execution generates and tests all permutations of aband we show the permutations generated directly below their respective boxes
20,850
exercises for source code and help with exercisesplease visit java datastructures net reinforcement - the add and remove methods of code fragments and do not keep track of the number,nof non-null entries in the arraya insteadthe unused cells point to the null object show how to change these methods so that they keep track of the actual size of in an instance variable - describe way to use recursion to add all the elements in (two dimensionalarray of integers - explain how to modify the caesar cipher program (code fragment so that it performs rot encryption and decryptionwhich uses as the alphabet shift amount how can you further simplify the code so that the body of the decrypt method is only single liner- explain the changes that would have be made to the program of code fragment so that it could perform the caesar cipher for messages that are written in an alphabet-based language other than englishsuch as greekrussianor hebrew - what is the exception that is thrown when advance or remove is called on an empty listfrom code fragment explain how to modify these methods so that they give more instructive exception name for this condition - give recursive definition of singly linked list - describe method for inserting an element at the beginning of singly linked list assume that the list does not have sentinel header nodeand instead uses variable head to reference the first node in the list
20,851
give an algorithm for finding the penultimate node in singly linked list where the last element is indicated by null next reference - describe nonrecursive method for findingby link hoppingthe middle node of doubly linked list with header and trailer sentinels (notethis method must only use link hoppingit cannot use counter what is the running time of this methodr- describe recursive algorithm for finding the maximum element in an array of elements what is your running time and space usager- draw the recursion trace for the execution of method reversearray ( , , (code fragment on array { , , , , - draw the recursion trace for the execution of method puzzlesolve( ,su(code fragment )where is empty and { , , ,dr- write short java method that repeatedly selects and removes random entry from an array until the array holds no more entries - write short java method to count the number of nodes in circularly linked list creativity - give java code for performing add(eand remove(imethods for game entriesstored in an array aas in code fragments and except now don' maintain the game entries in order assume that we still need to keep entries stored in indices to try to implement the add and remove methods without using any loopsso that the number of steps they perform does not depend on
20,852
let be an array of size > containing integers from to inclusivewith exactly one repeated describe fast algorithm for finding the integer in that is repeated - let be an array of size > containing integers from to inclusivewith exactly five repeated describe good algorithm for finding the five integers in that are repeated - suppose you are designing multi-player game that has > playersnumbered to ninteracting in an enchanted forest the winner of this game is the first player who can meet all the other players at least once (ties are allowedassuming that there is method meet( , )which is called each time player meets player (with )describe way to keep track of the pairs of meeting players and who is the winner - give recursive algorithm to compute the product of two positive integersm and nusing only addition and subtraction - describe fast recursive algorithm for reversing singly linked list lso that the ordering of the nodes becomes opposite of what it was beforea list has only one positionthen we are donethe list is already reversed otherwiseremove - describe good algorithm for concatenating two singly linked lists and mwith header sentinelsinto single list that contains all the nodes of followed by all the nodes of - give fast algorithm for concatenating two doubly linked lists and mwith header and trailer sentinel nodesinto single list - describe in detail how to swap two nodes and in singly linked list given references only to and repeat this exercise for the case when is doubly linked list which algorithm takes more time
20,853
describe in detail an algorithm for reversing singly linked list using only constant amount of additional space and not using any recursion - in the towers of hanoi puzzlewe are given platform with three pegsaband csticking out of it on peg is stack of diskseach larger than the nextso that the smallest is on the top and the largest is on the bottom the puzzle is to move all the disks from peg to peg cmoving one disk at timeso that we never place larger disk on top of smaller one see figure for an example of the case describe recursive algorithm for solving the towers of hanoi puzzle for arbitrary (hintconsider first the subproblem of moving all but the nth disk from peg to another peg using the third as "temporary storage figure puzzle an illustration of the towers of hanoi - describe recursive method for converting string of digits into the integer it represents for example" represents the integer , - describe recursive algorithm that counts the number of nodes in singly linked list -
20,854
elements (without repeating any subsetsc- write short recursive java method that finds the minimum and maximum values in an array of int values without using any loops - describe recursive algorithm that will check if an array of integers contains an integer [ithat is the sum of two integers that appear earlier in athat issuch that [ia[ + [kfor , - write short recursive java method that will rearrange an array of int values so that all the even values appear before all the odd values - write short recursive java method that takes character string and outputs its reverse so for examplethe reverse of "pots&panswould be "snap&stopc- write short recursive java method that determines if string is palindromethat isit is equal to its reverse for example"racecarand "gohangasalamiimalasagnahogare palindromes - use recursion to write java method for determining if string has more vowels than consonants - suppose you are given two circularly linked listsl and mthat istwo lists of nodes such that each node has nonnull next node describe fast algorithm for telling if and are really the same list of nodesbut with different (cursorstarting points - given circularly linked list containing an even number of nodesdescribe how to split into two circularly linked lists of half the size
20,855
- write java program for matrix class that can add and multiply arbitrary twodimensional arrays of integers - perform the previous projectbut use generic types so that the matrices involved can contain arbitrary number types - write class that maintains the top scores for game applicationimplementing the add and remove methods of section but using singly linked list instead of an array - perform the previous projectbut use doubly linked list moreoveryour implementation of remove(ishould make the fewest number of pointer hops to get to the game entry at index - perform the previous projectbut use linked list that is both circularly linked and doubly linked - write program for solving summation puzzles by enumerating and testing all possible configurations using your programsolve the three puzzles given in section - write program that can perform encryption and decryption using an arbitrary substitution cipher in this casethe encryption array is random shuffling of the letters in the alphabet your program should generate random encryption arrayits corresponding decryption arrayand use these to encode and decode message - write program that can perform the caesar cipher for english messages that include both upper and lowercase characters
20,856
the fundamental data structures of arrays and linked listsas well as recursiondiscussed in this belong to the folklore of computer science they were first chronicled in the computer science literature by knuth in his seminal book on fundamental algorithms [ analysis tools contents the seven functions used in this book the constant function the logarithm function the linear function
20,857
the -log- function the quadratic function the cubic function and other polynomials the exponential function comparing growth rates analysis of algorithms experimental studies
20,858
asymptotic notation asymptotic analysis using the big-oh notation recursive algorithm for computing powers simple justification techniques by example the "contraattack
20,859
induction and loop invariants exercises java datastructures net the seven functions used in this book in this sectionwe briefly discuss the seven most important functions used in the analysis of algorithms we will use only these seven simple functions for almost all the analysis we do in this book in facta section that uses function other than one of these seven will be marked with star to indicate that it is optional in addition to these seven fundamental functionsappendix contains list of other useful mathematical facts that apply in the context of data structure and algorithm analysis the constant function the simplest function we can think of is the constant function this is the functionf(ncfor some fixed constant csuch as or that isfor any argument nthe constant function (nassigns the value in other wordsit doesn' matter what the value of isf (nwill always be equal to the constant value since we are most interested in integer functionsthe most fundamental constant function is ( and this is the typical constant function we use in this book note that any other constant functionf(nccan be written as constant times (nthat is, (ncg(nin this case as simple as it isthe constant function is useful in algorithm analysisbecause it characterizes the number of steps needed to do basic operation on computerlike adding two numbersassigning value to some variableor comparing two numbers
20,860
one of the interesting and sometimes even surprising aspects of the analysis of data structures and algorithms is the ubiquitous presence of the logarithm functionf(nlog nfor some constant this function is defined as followsx log if and only if bx by definitionlog the value is known as the base of the logarithm computing the logarithm function exactly for any integer involves the use of calculusbut we can use an approximation that is good enough for our purposes without calculus in particularwe can easily compute the smallest integer greater than or equal to log nfor this number is equal to the number of times we can divide by until we get number less than or equal to for examplethis evaluation of log is since / likewisethis evaluation of log is since / / and this approximation to log is since / / < this base-two approximation arises in algorithm analysisactuallysince common operation in many algorithms is to repeatedly divide an input in half indeedsince computers store integers in binarythe most common base for the logarithm function in computer science is in factthis base is so common that we will typically leave it off when it is that isfor uslogn log we note that most handheld calculators have button marked logbut this is typically for calculating the logarithm base- not base-two there are some important rules for logarithmssimilar to the exponent rules proposition (logarithm rules)given real numbers and we have log ac log log log / log alog log ac clog log (log )/log log log alsoas notational shorthandwe use logcn to denote the function (logn) rather than show how we could derive each of the identities above which all follow from the definition of logarithms and exponentslet us illustrate these identities with few examples instead
20,861
logarithm rules from proposition (using the usual convention that the base of logarithm is if it is omittedlog( nlog log lognby rule log( / logn log logn by rule logn lognby rule log nlog = nby rule log (log )log (logn/ by rule logn nlog nby rule as practical matterwe note that rule gives us way to compute the base-two logarithm on calculator that has base- logarithm buttonlogfor log logn/log the linear function another simple yet important function is the linear functionf( ) that isgiven an input value nthe linear function assigns the value itself this function arises in algorithm analysis any time we have to do single basic operation for each of elements for examplecomparing number to each element of an array of size will require comparisons the linear function also represents the best running time we can hope to achieve for any algorithm that processes collection of objects that are not already in the computer' memorysince reading in the objects itself requires operations the -log- function the next function we discuss in this section is the -log- functionf(nnlognthat isthe function that assigns to an input the value of times the logarithm base-two of this function grows little faster than the linear function and lot slower than the quadratic function thusas we will show on several occasionsif we can improve the running time of solving some problem from quadratic to -lognwe will have an algorithm that runs much faster in general
20,862
another function that appears quite often in algorithm analysis is the quadratic functionf(nn that isgiven an input value nthe function assigns the product of with itself (in other words" squared"the main reason why the quadratic function appears in the analysis of algo rithms is that there are many algorithms that have nested loopswhere the inner loop performs linear number of operations and the outer loop is performed linear number of times thusin such casesthe algorithm performs operations nested loops and the quadratic function the quadratic function can also arise in the context of nested loops where the first iteration of loop uses one operationthe second uses two operationsthe third uses three operationsand so on that isthe number of operations is ( ( in other wordsthis is the total number of operations that will be performed by the nested loop if the number of operations performed inside the loop increases by one with each iteration of the outer loop this quantity also has an interesting history in german schoolteacher decided to keep his and -year-old pupils occupied by adding up the integers from to but almost immediately one of the children claimed to have the answerthe teacher was suspiciousfor the student had only the answer on his slate but the answer was correct-- , -and the studentcarl gaussgrew up to be one of the greatest mathematicians of his time it is widely suspected that young gauss used the following identity proposition for any integer > we have ( ( ( )/ we give two "visualjustifications of proposition in figure figure visual justifications of proposition both illustrations visualize the identity in terms of the total area covered by unit-width rectangles with heights , , in (athe rectangles are shown to
20,863
plus small triangles of area / each (base and height in ( )which applies only when is eventhe rectangles are shown to cover big rectangle of base / and height the lesson to be learned from proposition is that if we perform an algorithm with nested loops such that the operations in the inner loop increase by one each timethen the total number of operations is quadratic in the number of timesnwe perform the outer loop in particularthe number of operations is / / in this casewhich is little more than constant factor ( / times the quadratic function in other wordssuch an algorithm is only slightly better than an algorithm that uses operations each time the inner loop is performed this observation might at first seem nonintuitivebut it is nevertheless trueas shown in figure the cubic function and other polynomials continuing our discussion of functions that are powers of the inputwe consider the cubic functionf(nn
20,864
function appears less frequently in the context of algorithm analysis than the constantlinearand quadratic functions previously mentionedbut it does appear from time to time polynomials interestinglythe functions we have listed so far can be viewed as all being part of larger class of functionsthe polynomials polynomial function is function of the formf(na ndwhere , , are constantscalled the coefficients of the polynomialand integer dwhich indicates the highest power in the polynomialis called the degree of the polynomial for examplethe following functions are all polynomialsf( ( ( (nn (nn thereforewe could argue that this book presents just four important functions used in algorithm analysisbut we will stick to saying that there are sevensince the constantlinearand quadratic functions are too important to be lumped in with other polynomials running times that are polynomials with degreedare generally better than polynomial running times with large degree summations notation that appears again and again in the analysis of data structures and algorithms is the summationwhich is defined as follows
20,865
algorithm analysis because the running times of loops naturally give rise to summations using summationwe can rewrite the formula of proposition as likewisewe can write polynomial (nof degree with coefficients as thusthe summation notation gives us shorthand way of expressing sums of increasing terms that have regular structure the exponential function another function used in the analysis of algorithms is the exponential functionf(nbnwhere is positive constantcalled the baseand the argument is the exponent that isfunction (nassigns to the input argument the value obtained by multiplying the base by itself times in algorithm analysisthe most common base for the exponential function is for instanceif we have loop that starts by performing one operation and then doubles the number of operations performed with each iterationthen the number of operations performed in the nth iteration is in additionan integer word containing bits can represent all the nonnegative integers less than thusthe exponential function with base is quite common the exponential function will also be referred to as exponent function we sometimes have other exponents besides nhoweverhenceit is useful for us to know few handy rules for working with exponents in particularthe following exponent rules are quite helpful proposition (exponent rules)given positive integers , ,and ,we have (ba) bac babc ba+ ba/bc ba
20,866
( ) (exponent rule + (exponent rule / / - (exponent rule we can extend the exponential function to exponents that are fractions or real numbers and to negative exponentsas follows given positive integer kwe define / to be kth root of bthat isthe number such that rk for example / since likewise / and / this approach allows us to define any power whose exponent can be expressed as fractionfor ba/ (ba) /cby exponent rule for example / ( ) / / thusba/ is really just the cth root of the integral exponent ba we can further extend the exponential function to define bx for any real number xby computing series of numbers of the form ba/ for fractions / that get progressively closer and closer to any real number can be approximated arbitrarily close by fraction /chencewe can use the fraction / as the exponent of to get arbitrarily close to bx sofor examplethe number is well defined finallygiven negative exponent dwe define bd / -dwhich corresponds to applying exponent rule with and - geometric sums suppose we have loop where each iteration takes multiplicative factor longer than the previous one this loop can be analyzed using the following proposition proposition for any integer > and any real number such that and consider the summation (remembering that if this summation is equal to an / summations as shown in proposition are called geometric summationsbecause each term is geometrically larger than the previous one if for exampleeveryone working in computing should know that - -, for this is the largest integer that can be represented in binary notation using bits
20,867
to sum uptable shows each of the seven common functions used in algorithm analysiswhich we described abovein order table classes of functions here we assume that is constant constant logarithm linear -log- quadratic cubic exponent log nlogn an ideallywe would like data structure operations to run in times proportional to the constant or logarithm functionand we would like our algorithms to run in linear or -log- time algorithms with quadratic or cubic running times are less practicalbut algorithms with exponential running times are infeasible for all but the smallest sized inputs plots of the seven functions are shown in figure figure growth rates for the seven fundamental functions used in algorithm analysis we use base for the exponential function the functions are plotted in log-log chartto compare the growth rates
20,868
grows too fast to display all its values on the chart alsowe use the scientific notation for numberswhereae+ denotes the ceiling and floor functions one additional comment concerning the functions above is in order the value of logarithm is typically not an integeryet the running time of an algorithm is usually expressed by means of an integer quantitysuch as the number of operations performed thusthe analysis of an algorithm may sometimes involve the use of thefloor function and ceiling functionwhich are defined respectively as follows the largest integer less than or equal to the smallest integer greater than or equal to analysis of algorithms in classic storythe famous mathematician archimedes was asked to determine if golden crown commissioned by the king was indeed pure goldand not part silveras an informant had claimed archimedes discovered way to perform this analysis while stepping into (greekbath he noted that water spilled out of the bath in proportion to the amount of him that went in realizing the implications of this facthe immediately got out of the bath and ran naked through the city shouting"eurekaeureka!,for he had discovered an analysis tool (displacement)whichwhen combined with simple scalecould determine if the king' new crown was good or not that isarchimedes could dip the crown and an equal-weight amount of gold
20,869
was unfortunate for the goldsmithhoweverfor when archimedes did his analysisthe crown displaced more water than an equal-weight lump of pure goldindicating that the crown was notin factpure gold in this bookwe are interested in the design of "gooddata structures and algorithms simply puta data structure is systematic way of organizing and accessing dataand an algorithm is step-by-step procedure for performing some task in finite amount of time these concepts are central to computingbut to be able to classify some data structures and algorithms as "good,we must have precise ways of analyzing them the primary analysis tool we will use in this book involves characterizing the running times of algorithms and data structure operationswith space usage also being of interest running time is natural measure of "goodness,since time is precious resource--computer solutions should run as fast as possible in generalthe running time of an algorithm or data structure method increases with the input sizealthough it may also vary for different inputs of the same size alsothe running time is affected by the hardware environment (as reflected in the processorclock ratememorydisketc and software environment (as reflected in the operating systemprogramming languagecompilerinterpreteretc in which the algorithm is implementedcompiledand executed all other factors being equalthe running time of the same algorithm on the same input data will be smaller if the computer hassaya much faster processor or if the implementation is done in program compiled into native machine code instead of an interpreted implementation run on virtual machine neverthelessin spite of the possible variations that come from different environmental factorswe would like to focus on the relationship between the running time of an algorithm and the size of its input we are interested in characterizing an algorithm' running time as function of the input size but what is the proper way of measuring itexperimental studies if an algorithm has been implementedwe can study its running time by executing it on various test inputs and recording the actual time spent in each execution fortunatelysuch measurements can be taken in an accurate manner by using system calls that are built into the language or operating system (for exampleby using the system current time millis (method or calling the run-time environment with profiling enabledsuch tests assign specific running time to specific input sizebut we are interested in determining the general dependence of running time on the size of the input in order to determine this dependencewe should perform several experiments on many different test inputs of various sizes then we can visualize the results of such experiments by plotting the performance of each run of the algorithm as point with -coordinate equal to the input sizen
20,870
visualization and the data that supports itwe can perform statistical analysis that seeks to fit the best function of the input size to the experimental data to be meaningfulthis analysis requires that we choose good sample inputs and test enough of them to be able to make sound statistical claims about the algorithm' running time figure results of an experimental study on the running time of an algorithm dot with coordinates (ntindicates that on an input of size nthe running time of the algorithm is milliseconds (mswhile experimental studies of running times are usefulthey have three major limitationsexperiments can be done only on limited set of test inputshencethey leave out the running times of inputs not included in the experiment (and these inputs may be important
20,871
we will have difficulty comparing the experimental running times of two algorithms unless the experiments were performed in the same hardware and software environments we have to fully implement and execute an algorithm in order to study its running time experimentally this last requirement is obviousbut it is probably the most time consuming aspect of performing an experimental analysis of an algorithm the other limitations impose serious hurdles tooof course thuswe would ideally like to have an analysis tool that allows us to avoid performing experiments in the rest of this we develop general way of analyzing the running times of algorithms thattakes into account all possible inputs allows us to evaluate the relative efficiency of any two algorithms in way that is independent from the hardware and software environment can be performed by studying high-level description of the algorithm without actually implementing it or running experiments on it this methodology aims at associatingwith each algorithma function (nthat characterizes the running time of the algorithm as function of the input size typical functions that will be encountered include the seven functions mentioned earlier in this primitive operations as noted aboveexperimental analysis is valuablebut it has its limitations if we wish to analyze particular algorithm without performing experiments on its running timewe can perform an analysis directly on the high-level pseudo-code instead we define set of primitive operations such as the followingassigning value to variable calling method performing an arithmetic operation (for exampleadding two numberscomparing two numbers indexing into an array following an object reference returning from method
20,872
specificallya primitive operation corresponds to low-level instruction with an execution time that is constant instead of trying to determine the specific execution time of each primitive operationwe will simply count how many primitive operations are executedand use this number as measure of the running-time of the algorithm this operation count will correlate to an actual running time in specific computerfor each primitive operation corresponds to constant-time instructionand there are only fixed number of primitive operations the implicit assumption in this approach is that the running times of different primitive operations will be fairly similar thusthe numbertof primitive operations an algorithm performs will be proportional to the actual running time of that algorithm an algorithm may run faster on some inputs than it does on others of the same size thuswe may wish to express the running time of an algorithm as the function of the input size obtained by taking the average over all possible inputs of the same size unfortunatelysuch an average-case analysis is typically quite challenging it requires us to define probability distribution on the set of inputswhich is often difficult task figure schematically shows howdepending on the input distributionthe running time of an algorithm can be anywhere between the worst-case time and the best-case time for examplewhat if inputs are really only of types "aor " "figure the difference between best-case and worst-case time each bar represents the running time of some algorithm on different possible input
20,873
an average-case analysis usually requires that we calculate expected running times based on given input distributionwhich usually involves sophisticated probability theory thereforefor the remainder of this bookunless we specify otherwisewe will characterize running times in terms of the worst caseas function of the input sizenof the algorithm worst-case analysis is much easier than average-case analysisas it requires only the ability to identify the worst-case inputwhich is often simple alsothis approach typically leads to better algorithms making the standard of success for an algorithm to perform well in the worst case necessarily requires that it will do well on every input that isdesigning for the worst case leads to stronger algorithmic "muscles,much like track star who always practices by running up an incline asymptotic notation in generaleach basic step in pseudo-code description or high-level language implementation corresponds to small number of primitive operations (except for method callsof coursethuswe can perform simple analysis of an algorithm written in pseudo-code that estimates the number of primitive operations executed up to constant factorby pseudo-code steps (but we must be carefulsince single line of pseudo-code may denote number of steps in some cases
20,874
in algorithm analysiswe focus on the growth rate of the running time as function of the input size ntaking "big-pictureapproachrather than being bogged down with small details it is often enough just to know that the running time of an algorithm such as arraymaxgiven in section grows proportionally to nwith its true running time being times constant factor that depends on the specific computer we analyze data structures and algorithms using mathematical notation for functions that disregards constant factors namelywe characterize the running times of algorithms by using functions that map the size of the inputnto values that correspond to the main factor that determines the growth rate in terms of we do not formally define what meanshoweverand instead let refer to chosen measure of the input "size,which is allowed to be defined differently for each algorithm we are analyzing this approach allows us to focus attention on the primary "big-pictureaspects in running time function in additionthe same approach lets us characterize space usage for data structures and algorithmswhere we define space usage to be the total number of memory cells used the "big-ohnotation let (nand (nbe functions mapping nonnegative integers to real numbers we say that (nis ( ( )if there is real constant and an integer constant > such that (nn this definition is often referred to as the "big-ohnotationfor it is sometimes pronounced as " (nis big-oh of (nalternativelywe can also say " (nis order of ( (this definition is illustrated in figure figure illustrating the "big-ohnotation the function (nis ( ( ))since ( =
20,875
justificationby the big-oh definitionwe need to find real constant and an integer constant > such that it is easy to see that possible choice is and indeedthis is one of infinitely many choices available because any real number greater than or equal to will work for cand any integer greater than or equal to will work for the big-oh notation allows us to say that function (nis "less than or equal toanother function (nup to constant factor and in the asymptotic sense as grows toward infinity this ability comes from the fact that the definition uses "<=to compare (nto (ntimes constantcfor the asymptotic cases when >= characterizing running times using the big-oh notation the big-oh notation is used widely to characterize running times and space bounds in terms of some parameter nwhich varies from problem to problembut is always defined as chosen measure of the "sizeof the problem for exampleif we are interested in finding the largest element in an array of integersas in the arraymax algorithmwe should let denote the number of elements of the array using the big-oh notationwe can write the following mathematically precise statement on the running time of algorithm arraymax for any computer
20,876
element in an array ofn integersruns in (ntime justificationthe number of primitive operations executed by algorithm arraymax in each iteration is constant hencesince each primitive operation runs in constant timewe can say that the running time of algorithm arraymax on an input of size is at most constant times nthat iswe may conclude that the running time of algorithm arraymax is (nsome properties of the big-oh notation the big-oh notation allows us to ignore constant factors and lower order terms and focus on the main components of function that affect its growth example is ( justificationnote that <( ) cn for when > in factwe can characterize the growth rate of any polynomial function proposition if (nis polynomial of degree dthat isf(na na ndand then (nis (ndjustificationnote thatfor > we have < < <<ndhencea nd <( )nd thereforewe can show (nis (ndby defining and thusthe highest-degree term in polynomial is the term that determines the asymptotic growth rate of that polynomial we consider some additional properties of the big-oh notation in the exercises let us consider some further examples herehoweverfocusing on combinations of the seven fundamental functions used in algorithm design example nlog is (
20,877
when > (note that log is zero for example log is ( justification log example log is (log njustification log note that log is zero for that is why we use > in this case example + is ( njustification + * nhencewe can take and in this case example log is (njustification log hencewe can take in this case characterizing functions in simplest terms in generalwe should use the big-oh notation to characterize function as closely as possible while it is true that the function ( is ( or even ( )it is more accurate to say that (nis ( considerby way of analogya scenario where hungry traveler driving along long country road happens upon local farmer walking home from market if the traveler asks the farmer how much longer he must drive before he can find some foodit may be truthful for the farmer to say"certainly no longer than hours,but it is much more accurate (and helpfulfor him to say"you can find market just few minutes drive up this road thuseven with the big-oh notationwe should strive as much as possible to tell the whole truth it is also considered poor taste to include constant factors and lower order terms in the big-oh notation for exampleit is not fashionable to say that the function
20,878
to describe the function in the big-oh in simplest terms the seven functions listed in section are the most common functions used in conjunction with the big-oh notation to characterize the running times and space usage of algorithms indeedwe typically use the names of these functions to refer to the running times of the algorithms they characterize sofor examplewe would say that an algorithm that runs in worst-case time log as quadratic-time algorithmsince it runs in ( time likewisean algorithm running in time at most log would be called linear-time algorithm big-omega just as the big-oh notation provides an asymptotic way of saying that function is "less than or equal toanother functionthe following notations provide an asymptotic way of saying that function grows at rate that is "greater than or equal tothat of another let (nand (nbe functions mapping nonnegative integers to real numbers we say that (nis ohm( ( )(pronounced " (nis big-omega of ( )"if (nis ( ( )that isthere is real constant and an integer constant > such that ( >=cg( )for > this definition allows us to say asymptotically that one function is greater than or equal to anotherup to constant factor example nlog is ohm( log njustification log > log nfor > big-theta in additionthere is notation that allows us to say that two functions grow at the same rateup to constant factors we say that (nis th ( ( )(pronounced " (nis big-theta of ( )"if (nis ( ( )and (nis ohm( ( )that isthere are real constants and ' and an integer constant > such that ' (nn example log log isth( log njustification log
20,879
suppose two algorithms solving the same problem are availablean algorithm awhich has running time of ( )and an algorithm bwhich has running time of ( which algorithm is betterwe know that is ( )which implies that algorithm is asymptotically better than algorithm balthough for small value of nb may have lower running time than we can use the big-oh notation to order classes of functions by asymptotic growth rate our seven functions are ordered by increasing growth rate in the sequence belowthat isif function (nprecedes function (nin the sequencethen (nis ( ( )) log nlog we illustrate the growth rates of some important functions in figure table selected values of fundamental functions in algorithm analysis logn nlogn
20,880
, , , , , , , , ,
20,881
, , , , , , , , , , , we further illustrate the importance of the asymptotic viewpoint in table this table explores the maximum size allowed for an input instance that is processed by an algorithm in second minuteand hour it shows the importance of good algorithm designbecause an asymptotically slow algorithm is beaten in the long run by an asymptotically faster algorithmeven if the constant factor for the asymptotically faster algorithm is worse table maximum size of problem that can be solved in second minute,and hourfor various running times measured in microseconds
20,882
maximum problem size (ntime (ms second minute hour , , , , , , the importance of good algorithm design goes beyond just what can be solved effectively on given computerhowever as shown in table even if we achieve dramatic speed-up in hardwarewe still cannot overcome the handicap of an asymptotically slow algorithm this table shows the new maximum problem size achievable for any fixed amount of timeassuming algorithms with the given running times are now run on computer times faster than the previous one table increase in the maximum size of problem that can be solved in fixed amount of timeby using computer that is times faster than the previous one
20,883
problem size running time new maximum problem size + using the big-oh notation having made the case of using the big-oh notation for analyzing algorithmslet us briefly discuss few issues concerning its use it is considered poor tastein generalto say " ( < ( ( )),since the big-oh already denotes the "less-than-orequal-toconcept likewisealthough commonit is not fully correct to say " (no( ( ))(with the usual understanding of the "=relation)since there is no way to make sense of the statement " ( ( ) (nin additionit is completely wrong to say " ( > ( ( ))or " (no( ( )),since the (nin the big-oh expresses an upper bound on (nit is best to say" (nis ( ( )for the more mathematically inclinedit is also correct to say" (no( ( )),for the big-oh notation istechnically speakingdenoting whole collection of functions in this bookwe will stick to presenting big-oh statements as " (nis ( ( )even with this interpretationthere is considerable freedom in how we can use arithmetic operations with the big-oh notationand with this freedom comes certain amount of responsibility some words of caution few words of caution about asymptotic notation are in order at this point firstnote that the use of the big-oh and related notations can be somewhat misleading
20,884
that the function is ( )if this is the running time of an algorithm being compared to one whose running time is nlognwe should prefer the (nlogntime algorithmeven though the linear-time algorithm is asymptotically faster this preference is because the constant factor which is called "one googol,is believed by many astronomers to be an upper bound on the number of atoms in the observable universe so we are unlikely to ever have real-world problem that has this number as its input size thuseven when using the big-oh notationwe should at least be somewhat mindful of the constant factors and lower order terms we are "hiding the observation above raises the issue of what constitutes "fastalgorithm generally speakingany algorithm running in (nlogntime (with reasonable constant factorshould be considered efficient even an ( time method may be fast enough in some contextsthat iswhen is small but an algorithm running in ( ntime should almost never be considered efficient exponential running times there is famous story about the inventor of the game of chess he asked only that his king pay him grain of rice for the first square on the board grains for the second grains for the third for the fourthand so on it is an interesting test of programming skills to write program to compute exactly the number of grains of rice the king would have to pay in factany java program written to compute this number in single integer value will cause an integer overflow to occur (although the run-time machine will probably not complainto represent this number exactly as an integer requires using biginteger class if we must draw line between efficient and inefficient algorithmsthereforeit is natural to make this distinction be that between those algorithms running in polynomial time and those running in exponential time that ismake the distinction between algorithms with running time that is (nc)for some constant and those with running time that is (bn)for some constant like so many notions we have discussed in this sectionthis too should be taken with "grain of salt,for an algorithm running in ( time should probably not be considered "efficient even sothe distinction between polynomial-time and exponential-time algorithms is considered robust measure of tractability to summarizethe asymptotic notations of big-ohbig-omegaand big-theta provide convenient language for us to analyze data structures and algorithms as mentioned earlierthese notations provide convenience because they let us concentrate on the "big picturerather than low-level details two examples of asymptotic algorithm analysis
20,885
problem but have rather different running times the problem we are interested in is the one of computing the so-called prefix averages of sequence of numbers namelygiven an array storing numberswe want to compute an array such that [iis the average of elements [ ] [ ]for that iscomputing prefix averages has many applications in economics and statistics for examplegiven the year-by-year returns of mutual fundan investor will typically want to see the fund' average annual returns for the last yearthe last three yearsthe last five yearsand the last ten years likewisegiven stream of daily web usage logsa web site manager may wish to track average usage trends over various time periods quadratic-time algorithm our first algorithm for the prefix averages problemcalled prefixaverages is shown in code fragment it computes every element of separatelyfollowing the definition code fragment algorithm prefixaverages let us analyze the prefixaverages algorithm initializing and returning array at the beginning and end can be done with constant number of primitive operations per elementand takes (ntime
20,886
there are two nested for loopswhich are controlled by counters and jrespectively the body of the outer loopcontrolled by counter iis executed timesfor , thusstatements and [ia/( are executed times each this implies that these two statementsplus the incrementing and testing of counter icontribute number of primitive operations proportional to nthat iso(ntime the body of the inner loopwhich is controlled by counter jis executed timesdepending on the current value of the outer loop counter thusstatement [jin the inner loop is executed + times by recalling proposition we know that +nn( )/ which implies that the statement in the inner loop contributes ( time similar argument can be done for the primitive operations associated with the incrementing and testing counter jwhich also take ( )time the running time of algorithm prefixaverages is given by the sum of three terms the first and the second term are ( )and the third term is ( by simple application of proposition the running time of prefixaverages is ( linear-time algorithm in order to compute prefix averages more efficientlywe can observe that two consecutive averages [ and [iare similara[ ( [ [ [ ])/ [ ( [ [ [ [ ])/( if we denote with the prefix sum [ [ [ ]we can compute the prefix averages as [is /( it is easy to keep track of the current prefix sum while scanning array with loop we are now ready to present algorithm prefixaverages in code fragment code fragment algorithmprefix averages
20,887
initializing and returning array at the beginning and end can be done with constant number of primitive operations per elementand takes (ntime initializing variable at the beginning takes ( time there is single for loopwhich is controlled by counter the body of the loop is executed timesfor , thusstatements [iand [is/( are executed times each this implies that these two statements plus the incrementing and testing of counter contribute number of primitive operations proportional to nthat iso(ntime the running time of algorithm prefixaverages is given by the sum of three terms the first and the third term are ( )and the second term is ( by simple application of proposition the running time of prefixaverages is ( )which is much better than the quadratic-time algorithm prefixaverages recursive algorithm for computing powers as more interesting example of algorithm analysislet us consider the problem of raising number to an arbitrary nonnegative integern that iswe wish to compute the power function ( , )defined as ( ,nxn this function has an immediate recursive definition based on linear recursion
20,888
calls to compute ( ,nwe can compute the power function much faster than thishoweverby using the following alternative definitionalso based on linear recursionwhich employs squaring techniqueto illustrate how this definition worksconsider the following examples ( / ) ( / ) ( ) ( / ) ( / ) ( ) ( ( / ) ( / ) ( ) ( / ) ( / ) ( ) ( this definition suggests the algorithm of code fragment code fragment computing the power function using linear recursion to analyze the running time of the algorithmwe observe that each recursive call of method power(xndivides the exponentnby two thusthere are (lognrecursive callsnot (nthat isby using linear recursion and the squaring
20,889
from (nto (logn)which is big improvement simple justification techniques sometimeswe will want to make claims about an algorithmsuch as showing that it is correct or that it runs fast in order to rigorously make such claimswe must use mathematical languageand in order to back up such claimswe must justify or prove our statements fortunatelythere are several simple ways to do this by example some claims are of the generic form"there is an element in set that has property to justify such claimwe only need to produce particular in that has property likewisesome hard-to-believe claims are of the generic form"every element in set has property to justify that such claim is falsewe need to only produce particular from that does not have property such an instance is called counterexample example professor amongus claims that every number of the form is primewhen is an integer greater than professor amongus is wrong justificationto prove professor amongus is wrongwe find counterexample fortunatelywe need not look too farfor the "contraattack another set of justification techniques involves the use of the negative the two primary such methods are the use of the contrapositive and the contradiction the use of the contrapositive method is like looking through negative mirror to justify the statement "if is truethen is truewe establish that "if is not truethen is not trueinstead logicallythese two statements are the samebut the latterwhich is called the contrapositive of the firstmay be easier to think about example let and be integers if ab is eventhen is even or is even justificationto justify this cxlaimconsider the contrapositive"if is odd and is oddthen ab is odd sosuppose and + for some integers and then ab ij ( ij plusi henceab is odd
20,890
example also contains an application of demorgan' law this law helps us deal with negationsfor it states that the negation of statement of the form " or qis "not and not likewiseit states that the negation of statement of the form " and qis "not or not qcontradiction another negative justification technique is justification by contradictionwhich also often involves using demorgan' law in applying the justification by contradicti on techniquewe establish that statement is true by first supposing that is false and then showing that this assumption leads to contradiction (such as or by reaching such contradictionwe show that no consistent situation exists with being falseso must be true of coursein order to reach this conclusionwe must be sure our situation is consistent before we assume is false example let and be integers if ab is oddthen is odd and is odd justificationlet ab be odd we wish to show that is odd and is odd sowith the hope of leading to contradictionlet us assume the oppositenamelysuppose is even or is even in factwithout loss of generalitywe can assume that is even (since the case for is symmetricthen for some integer henceab ( ) (ib)that isab is even but this is contradictionab cannot simultaneously be odd and even therefore is odd and is odd induction and loop invariants most of the claims we make about running time or space bound involve an integer parameter (usually denoting an intuitive notion of the "sizeof the problemmoreovermost of these claims are equivalent to saying some statement (nis true "for all > since this is making claim about an infinite set of numberswe cannot justify this exhaustively in direct fashion induction we can often justify claims such as those above as truehoweverby using the technique of induction this technique amounts to showing thatfor any particular > there is finite sequence of implications that starts with something known to be true and ultimately leads to showing that (nis true specificallywe begin justification by induction by showing that (nis true for (and possibly some other values , kfor some constant kthen
20,891
true for nthen (nis true the combination of these two pieces completes the justification by induction proposition consider the fibonacci function ( )where we define ( ( and (nf( ( for (see section we claim thatf( justificationwe will show our claim is right by induction base cases( < ( and ( induction step( suppose our claim is true for consider (nsince (nf( ( moreoversince < and nwe can apply the inductive assumption (sometimes called the "inductive hypothesis"to imply that ( since - - - - let us do another inductive argumentthis time for fact we have seen before proposition (which is the same as proposition justificationwe will justify this equality by induction base casen trivialfor ( )/ if induction stepn > assume the claim is true for consider by the induction hypothesisthen which we can simplify as ( ) / / / ( )/
20,892
all >= we should rememberhoweverthe concreteness of the inductive technique it shows thatfor any particular nthere is finite step-by-step sequence of implications that starts with something true and leads to the truth about in shortthe inductive argument is formula for building sequence of direct justifications loop invariants the final justification technique we discuss in this section is the loop invariant to prove some statement about loop is correctdefine in terms of series of smaller statements , where the initial claims is true before the loop begins if - is true before iteration ithen will be true after iteration the final statements implies the statement that we wish to be true we havein factseen loop-invariant argument in section (for the correctness of algorithm arraymax)but let us give one more example here in particularlet us consider using loop invariant to justify the correctness of arrayfindshown in code fragment for finding an element in an array code fragment algorithm arrayfind for finding given element in an array to show that arrayfind is correctwe inductively define series of statementss that lead to the correctness of our algorithm specificallywe claim the following is true at the beginning of iteration of the while loops is not equal to any of the first elements of
20,893
no elements among the first in (this kind of trivially true claim is said to hold vacuouslyin iteration iwe compare element to element [iand return the index if these two elements are equalwhich is clearly correct and completes the algorithm in this case if the two elements and [iare not equalthen we have found one more element not equal to and we increment the index thusthe claim will be true for this new value of ihenceit is true at the beginning of the next iteration if the while-loop terminates without ever returning an index in athen we have that iss is true--there are no elements of equal to thereforethe algorithm correctly returns -- to indicate that is not in exercises for source code and help with exercisesplease visit java datastructures net reinforcement - give pseudo-code description of the ( )-time algorithm for computing the power function (xnalsodraw the recursion trace of this algorithm for the computation of ( , - give java description of algorithm power for computing the power function (xn(code fragment - draw the recursion trace of the power algorithm (code fragment which computes the power function ( , )for computing ( , - analyze the running time of algorithm binarysum (code fragment for arbitrary values of the input parameter - graph the functions nlogn and using logarithmic scale for the xand -axes that isif the function value (nis yplot this as point with xcoordinate at log and -coordinate at log -
20,894
respectively determine such that is better than for > - the number of operations executed by algorithms and is and respectively determine such that is better than for > - give an example of function that is plotted the same on log-log scale as it is on standard scale - explain why the plot of the function nc is straight line with slope on loglog scale - what is the sum of all the even numbers from to nfor any positive integer nr- show that the following two statements are equivalent(athe running time of algorithm is ( ( )(bin the worst casethe running time of algorithm is ( ( ) - order the following functions by asymptotic growth rate log logn + log log - show that if (nis ( ( ))then ad(nis ( ( ))for any constant >
20,895
show that if (nis ( ( )and (nis ( ( ))then the product ( ) (nis ( ( ) ( ) - give big-oh characterizationin terms of nof the running time of the ex method shown in code fragment - give big-oh characterizationin terms of nof the running time of the ex method shown in code fragment - give big-oh characterizationin terms of nof the running time of the ex method shown in code fragment - give big-oh characterizationin terms of nof the running time of the ex method shown in code fragment - give big-oh characterizationin terms of nof the running time of the ex method shown in code fragment - bill has an algorithmfind dto find an element in an array the algorithm find iterates over the rows of aand calls the algorithm array findof code fragment on each rowuntil is found or it has searched all rows of what is the worst-case running time of find in terms of nwhat is the worst-case running time of find in terms of nwhere is the total size of awould it be correct to say that find is linear-time algorithmwhy or why notr- for each function (nand time in the following tabledetermine the largest size of problem that can be solved in time if the algorithm for solving takes (nmicroseconds (one entry is already completed
20,896
show that if (nis ( ( )and (nis ( ( ))then (ne(nis ( (ng( ) - show that if (nis ( ( )and (nis ( ( ))then (ne(nis not necessarily of(ng( ) - show that if (nis ( ( )and (nis ( ( ))then (nis ( ( ) - show that (max{ ( ), ( )} ( (ng( ) - show that (nis ( ( )if and only if (nis ohm( ( ) - show that if (nis polynomial in nthen log (nis (lognr- show that ( ) is ( code fragment some algorithms
20,897
show that + is ( nr- show that is (nlognr- show that is ohm( log nr- show that nlogn is ohm(nr- show that [ ( )is ( ( ))if (nis positive nondecreasing function that is always greater than - algorithm executes an (logn)-time computation for each entry of an nelement array what is the worst-case running time of algorithm ar- given an -element array xalgorithm chooses logn elements in at random and executes an ( )-time calculation for each what is the worst-case running time of algorithm br- given an -element array of integersalgorithm executes an ( )-time computation for each even number in xand an (logn)-time computation for each odd number in what are the best-case and worst-case running times of algorithm cr- given an -element array xalgorithm calls algorithm on each element [ialgorithm runs in (itime when it is called on element [iwhat is the worst-case running time of algorithm dr- al and bob are arguing about their algorithms al claims his (nlogn)-time method is always faster than bob' ( )-time method to settle the issuethey
20,898
( )-time algorithm runs fasterand only when > is the ( log -time one better explain how this is possible creativity - describe recursive algorithm to compute the integer part of the base-two logarithm of using only addition and integer division - describe how to implement the queue adt using two stacks what is the running time of the enqueue(and dequeue(methods in this casec- suppose you are given an -element array containing distinct integers that are listed in increasing order given number kdescribe recursive algorithm to find two integers in that sum to kif such pair exists what is the running time of your algorithmc- given an -element unsorted array of integers and an integer kdescribe recursive algorithm for rearranging the elements in so that all elements less than or equal to come before any elements larger than what is the running time of your algorithmc- show that is ( - show that geometric progression (hinttry to bound this sum term by term with - show that log (nis th(logf( )if is constant -
20,899
using fewer than / comparisons (hintfirst construct group of candidate minimums and group of candidate maximums - bob built web site and gave the url only to his friendswhich he numbered from to he told friend number that he/she can visit the web site at most times now bob has counterckeeping track of the total number of visits to the site (but not the identities of who visitswhat is the minimum value for such that bob should know that one of his friends has visited his/her maximum allowed number of timesc- consider the following "justificationthat the fibonacci functionf( (see proposition is ( ):base case ( < ) ( and ( induction step ( )assume claim true for consider (nf( ( by inductionf( is ( and ( is ( thenf(nis (( ( ))by the identity presented in exercise - thereforef(nis (nwhat is wrong with this "justification" - let (xbe polynomial of degree nthat is, ( (adescribe simple ( time method for computing ( (bnow consider rewriting of (xas (xa ( + ( ( ( - +xa )))which is known as horner' method using the big-oh notationcharacterize the number of arithmetic operations this method executes - consider the fibonacci functionf( (see proposition show by induction that (nis ohm(( / )nc-