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...
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 pseu...
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 th...
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 ...
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...
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 se...
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...
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 frag...
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 adv...
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 jus...
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 lis...
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 listprov...
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 poin...
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 unfortunat...
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 acces...
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 trail...
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 fig...
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 ...
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...
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 o...
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 getla...
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 li...
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 except...
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 simulat...
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 dif...
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 langu...
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 mor...
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 interva...
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 ...
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( recursi...
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 throu...
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...
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 arraya...
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 fo...
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 th...
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 t...
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 ...
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 app...
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...
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 c...
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...
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 recursi...
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 tr...
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 co...
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 repea...
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 an...
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 atha...
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...
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 ...
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...
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 computi...
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...
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 hav...
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 ti...
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 polynomia...
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 ...
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 all...
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 ...
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 express...
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 w...
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' ...
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...
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 al...
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 in...
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 ru...
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 f...
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 ...
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 fun...
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 t...
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 ti...
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...
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...
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-t...
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 astr...
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 applic...
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 ope...
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/(...
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 ( / ) ( / ) ( ) ( / ) ( / ) ( ) ( ( / ) ( / ) ( ) ( / ) ( /...
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 ...
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 justific...
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...
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 in...
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 mor...
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 straigh...
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 o...
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 nthe...
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...
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 runn...
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 ...