id
int64
0
25.6k
text
stringlengths
0
4.59k
20,900
efficient method for computing each of partial sums what is the running time of this methodfor , - draw visual justification of proposition analogous to that of figure (bfor the case when is odd - an array contains unique integers in the range [ , that isthere is one number from this range that is not in design an ( )-...
20,901
matrix recall that the product ab is defined so that [ [jwhat is the running time of your methodc- suppose each row of an array consists of ' and ' such thatin any row of all the ' come before any ' also suppose that the number of ' in row is at least the number in row for , assuming is already in memorydescribe method...
20,902
stacks and queues contents
20,903
the stack abstract data type simple array-based stack implementation implementing stack with generic linked list reversing an array using stack matching parentheses and html tags queues the queue abstract data type asimple array-based queue implementation
20,904
implementing queue with generic linked list round robin schedulers double-ended queues the deque abstract data type implementing deque exercises java datastructures net stacks stack is collection of objects that are inserted and removed according to the lastin first-out (lifoprinciple objects can be inserted into stack...
20,905
metaphor would be pez(rcandy dispenserwhich stores mint candies in springloaded container that "popsout the top-most candy in the stack when the top of the dispenser is lifted (see figure stacks are fundamental data structure they are used in many applicationsincluding the following figure schematic drawing of pez(rdis...
20,906
pop()remove from the stack and return the top element on the stackan error occurs if the stack is empty additionallylet us also define the following methodssize()return the number of elements in the stack isempty()return boolean indicating if the stack is empty top()return the top element in the stackwithout removing i...
20,907
( top( ( pop( (pop("error(isempty(true (push( ( push( ( push( ( push(
20,908
size( ( pop( ( push( ( pop( ( pop( ( stack interface in java because of its importancethe stack data structure is included as "built-inclass in the java util package of java class java util stack is data structure that stores generic java objects and includesamong othersthe methods push()pop()peek((equivalent to top())...
20,909
instancethe error condition that occurs when calling method pop(or top(on an empty stack is signaled by throwing an exception of type emptystackexceptionwhich is defined in code fragment code fragment exception thrown by methods pop(and top(of the stack interface when called on an empty stack complete java interface fo...
20,910
we can implement stack by storing its elements in an array specificallythe stack in this implementation consists of an -element array plus an integer variable that gives the the index of the top element in array (see figure figure implementing stack with an array the top element in the stack is stored in the cell [trec...
20,911
the correctness of the methods in the array-based implementation follows immediately from the definition of the methods themselves there isneverthelessa mildly interesting point here involving the implementation of the pop method note that we could have avoided resetting the old [tto null and we would still have correc...
20,912
if there are no other active references to ethen the memory space taken by will be reclaimed by the garbage collector table shows the running times for methods in realization of stack by an array each of the stack methods in the array realization executes constant number of statements involving arithmetic operationscom...
20,913
remainder of this book note that we use symbolic namecapacityto specify the capacity of the array this allows us to specify the capacity of the array in one place in our code and have that value reflected throughout code fragment array-based java implementation of the stack interface (continues in code fragment
20,914
array-based stack (continued from code fragment
20,915
belowwe show the output from the above arraystack program note thatthrough the use of generic typeswe are able to create an arraystack for storing integers and another arraystack that stores character strings new arraystack areturns null resultsize isempty truestack[ push( )returns null resultsize isempty falsestack[ p...
20,916
implementation has one negative aspect--it must assume fixed upper boundcapacityon the ultimate size of the stack in code fragment we chose the capacity value , more or less arbitrarily an application may actually need much less space than thiswhich would waste memory alternativelyan application may need more space tha...
20,917
java implementation of stackby means of generic singly linked listis given in code fragment all the methods of the stack interface are executed in constant time in addition to being time efficientthis linked list implementation has space requirement that is ( )where is the current number of elements in the stack thusth...
20,918
elements at the head of the list code fragment class nodestackwhich implements the stack interface using singly linked listwhose nodes are objects of class node from code fragment reversing an array using stack we can use stack to reverse the elements in an arraythereby producing nonrecursive algorithm for the array-re...
20,919
code fragment we give java implementation of this algorithm incidentallythis method also illustrates how we can use generic types in simple application that uses generic stack in particularwhen the elements are popped off the stack in this examplethey are automatically returned as elements of the typehencethey can be i...
20,920
in this subsectionwe explore two related applications of stacksthe first of which is for matching parentheses and grouping symbols in arithmetic expressions arithmetic expressions can contain various pairs of grouping symbolssuch as parentheses"(and ")braces"{and "}brackets"[and "]floor function symbolsceiling function...
20,921
correct)()){([)])correct(()()){([)])})incorrect)()){([)])incorrect({[])incorrectwe leave the precise definition of matching of grouping symbols to exercise - an algorithm for parentheses matching an important problem in processing arithmetic expressions is to make sure their grouping symbols match up correctly we can u...
20,922
another application in which matching is important is in the validation of html documents html is the standard format for hyperlinked documents on the internet in an html documentportions of text are delimited by html tags simple opening html tag has the form "and the corresponding closing tag has the form commonly use...
20,923
document(bits rendering fortunatelymore or less the same algorithm as in code fragment can be used to match the tags in an html document in code fragments and we give java program for matching tags in an html document read from standard input for simplicitywe assume that all tags are the simple opening or closing tags ...
20,924
matching tags in an html document (continued from method ishtmlmatched uses stack to store the names of the opening tags seen so farsimilar to how the stack was used in code fragment method parsehtml uses scanner to extract the tags from the html documentusing the pattern "]*>,which denotes string that starts with '<'f...
20,925
queue is collection of objects that are inserted and removed according to the firstin first-out (fifoprinciple that iselements can be inserted at any timebut only the element that has been in the queue the longest can be removed at any time we usually say that elements enter queue at the rear and are removed from the f...
20,926
( enqueue( ( dequeue ( enqueue( ( dequeue ( front ( dequeue (dequeue"error(isempty
20,927
(enqueue( ( enqueue( ( size( ( enqueue( ( enqueue( ( dequeue ( example applications there are several possible applications for queues storestheatersreservation centersand other similar services typically process customer requests according to the fifo principle queue would therefore be logical choice for data structur...
20,928
java interface for the queue adt is given in code fragment this generic interface specifies that objects of arbitrary object types can be inserted into the queue thuswe don' have to use explicit casting when removing elements note that the size and isempty methods have the same meaning as their counterparts in the stac...
20,929
we present simple realization of queue by means of an arrayqof fixed capacitystoring its elements since the main rule with the queue adt is that we insert and delete objects according to the fifo principlewe must decide how we are going to keep track of the front and rear of the queue
20,930
letting [ be the front of the queue and then letting the queue grow from there this is not an efficient solutionhoweverfor it requires that we move all the elements forward one array cell each time we perform dequeue operation such an implementation would therefore take (ntime to perform the dequeue methodwhere is the ...
20,931
array implementing this circular view of is actually pretty easy each time we increment or rwe compute this increment as "( mod nor "( mod ,respectively recall that operator "modis the modulo operatorwhich is computed by taking the remainder after an integral division for example divided by is with remainder so mod spe...
20,932
first consider the situation that occurs if we enqueue objects into without dequeuing any of them we would have rwhich is the same condition that occurs when the queue is empty hencewe would not be able to tell the difference between full queue and an empty one in this case fortunatelythis is not big problemand number ...
20,933
in the "wrapped aroundconfiguration (when fthe java implementation of queue by means of an array is similar to that of stackand is left as an exercise ( - table shows the running times of methods in realization of queue by an array as with our array-based stack implementationeach of the queue methods in the array reali...
20,934
array-based implementation is quite efficient implementing queue with generic linked list we can efficiently implement the queue adt using generic singly linked list for efficiency reasonswe choose the front of the queue to be at the head of the listand the rear of the queue to be at the tail of the list in this waywe ...
20,935
in ( time we also avoid the need to specify maximum size for the queueas was done in the array-based queue implementationbut this benefit comes at the expense of increasing the amount of space used per element stillthe methods in the singly linked list queue implementation are more complicated than we might likefor we ...
20,936
various applications running concurrently on computer we can implement round robin scheduler using queueqby repeatedly performing the following steps (see figure ) dequeue( service element enqueue(efigure the three iterative steps for using queue to implement round robin scheduler the josephus problem in the children' ...
20,937
after this process has been performed timeswe remove the front element by dequeuing it from the queue and discarding it we show complete java program for solving the josephus problem using this approach in code fragment which describes solution that runs in (nktime (we can solve this problem faster using techniques bey...
20,938
double-ended queues consider now queue-like data structure that supports insertion and deletion at both the front and the rear of the queue such an extension of queue is called doubleended queueor dequewhich is usually pronounced "deckto avoid confusion with the dequeue method of the regular queue adtwhich is pronounce...
20,939
addfirst( ( , removefirst( ( addlast( ( , removefirst( ( removelast( (removefirst("error(isempty(true (implementing deque
20,940
linked list to implement deque would be inefficient we can use doubly linked listhoweverto implement deque efficiently as discussed in section inserting or removing elements at either end of doubly linked list is straightforward to do in ( timeif we use sentinel nodes for the header and trailer for an insertion of new ...
20,941
in constant time we leave the details of implementing the deque adt efficiently in java as an exercise ( - incidentallyall of the methods of the deque adtas described aboveare included in the java util linkedlist class soif we need to use deque and would rather not implement one from scratchwe can simply use the built-...
20,942
class nodedeque implementing the deque interfaceexcept that we have not shown the class dlnodewhich is generic doubly linked list nodenor have we shown methods getlastaddlastand removefirst
20,943
exercises for source code and help with exercisesplease visit java datastructures net reinforcement - suppose an initially empty stack has performed total of push operations top operationsand pop operations of which generated stackemptyexceptionswhich were caught and ignored what is the current size of sr- if we implem...
20,944
operations front operationsand dequeue operations of which generated queueemptyexceptionswhich were caught and ignored what is the current size of qr- if the queue of the previous problem was implemented with an array of capacity as described in the and it never generated fullqueueexceptionwhat would be the current val...
20,945
in random order write shortstraightline piece of pseudo-code (with no loops or recursionthat uses only one comparison and only one variable xyet guarantees with probability / that at the end of this code the variable will store the largest of alice' three integers argue why your method is correct - describe how to impl...
20,946
alice has three array-based stacksaband csuch that has capacity has capacity and has capacity initiallya is fulland and are empty unfortunatelythe person who programmed the class for these stacks made the push and pop methods private the only method alice can use is static methodtransfer( , )which transfers (by itera-t...
20,947
exercise - and output its value - implement the queue adt using an array - implement the entire queue adt using singly linked list - design an adt for two-colordouble-stack adt that consists of two stacks-one "redand one "blue"--and has as its operations color-coded versions of the regular stack adt operations for exam...
20,948
"buy xshare(sat $ eachor "sell share(sat $ each,assuming that the transactions occur on consecutive days and the values and are integers given this input sequencethe output should be the total capital gain (or lossfor the entire sequenceusing the fifo protocol to identify shares notes we were introduced to the approach...
20,949
simple array-based implementation simple interface and the java util arraylist class implementing an array list using extendable arrays node lists node-based operations positions the node list abstract data type doubly linked list implementation
20,950
iterators the iterator and iterable abstract data types the java for-each loop implementing iterators list iterators in java list adts and the collections framework the java collections framework the java util linkedlist class
20,951
case studythe move-to-front heuristic using sorted list and nested class using list with the move-to-front heuristic possible uses of favorites list exercises java datastructures net array lists suppose we have collection of elements stored in certain linear orderso that we can refer to the elements in as firstsecondth...
20,952
than its indexso the first element is at rank the second is at rank and so on sequence that supports access to its elements by their indices is called an array list (or vectorusing an older termsince our index definition is more consistent with the way arrays are indexed in java and other programming languages (such as...
20,953
add( , ( , get( ( , add( , ( , , get( "error( , , remove( ( , add( , ( , , add( , ( , , , add( ,
20,954
get( ( , , , , set( , ( , , , , the adapter pattern classes are often written to provide similar functionality to other classes the adapter design pattern applies to any context where we want to modify an existing class so that its methods match those of relatedbut differentclass or interface one general way for applyi...
20,955
addfirst(eadd( ,eaddlast(eadd(size(),eremovefirst(remove( removelast(remove(size( simple array-based implementation an obvious choice for implementing the array list adt is to use an array awhere [istores ( reference tothe element with index we choose the size of array sufficiently largeand we maintain the number of el...
20,956
array-based implementation of an array list that is storing elements(ashifting up for an insertion at index ( )shifting down for removal at index the performance of simple array-based implementation table shows the worst-case running times of the methods of an array list with elements realized by means of an array meth...
20,957
which runs in (ntimebecause we have to shift backward elements in the worst case ( in factassuming that each possible index is equally likely to be passed as an argument to these operationstheir average running time is ( )for we will have to shift / elements on average table performance of an array list with elements r...
20,958
in (ntime actuallywith little effortwe can produce an array-based implementation of the array list adt that achieves ( time for insertions and removals at index as well as insertions and removals at the end of the array list achieving this requires that we give up on our rule that an element at index is stored in the a...
20,959
of our simplified array list adt for examplethe class java util arraylist also includes methodclear()which removes all the elements from the array listand methodtoarray()which returns an array containing all the elements of the array list in the same order in additionthe class java util arraylist also has methods for s...
20,960
viewed as extending the end of the underlying array to make room for more elements (see figure intuitivelythis strategy is much like that of the hermit crabwhich moves into larger shell when it outgrows its previous one figure an illustration of the three steps for "growingan extendable array(acreate new array (bcopy e...
20,961
this array replacement strategy might at first seem slowfor performing single array replacement required by some element insertion can take (ntime still
20,962
new elements to the array list before the array must be replaced again this simple fact allows us to show that performing series of operations on an initially empty array list is actually quite efficient as shorthand notationlet us refer to the insertion of an element to be the last element in an array list as push ope...
20,963
extendable array with initial length one the total time to perform series of push operations in sstarting from being empty is (njustificationlet us assume that one cyber-dollar is enough to pay for the execution of each push operation in sexcluding the time spent for growing the array alsolet us assume that growing the...
20,964
node lists using an index is not the only means of referring to the place where an element appears in sequence if we have sequence implemented with (singly or doublylinked listthen it could possibly be more natural and efficient to use node instead of an index as means of identifying where to access and update in this ...
20,965
user to modify the internal structure of list without our knowledge such modification would be possiblehoweverif we provided reference to node in our list in form that allowed the user to access internal data in that node (such as next or prev fieldto abstract and unify the different ways of storing elements in the var...
20,966
error occurs if is the first position next( )return the position of the element of following the one at position pan error occurs if is the last position the above methods allow us to refer to relative positions in liststarting at the beginning or endand to move incrementally up or down the list these positions can int...
20,967
their placeswithout worrying about the exact way those places are represented (see figure figure node list the positions in the current order are pqrand there may at first seem to be redundancy in the above repertory of operations for the node list adtsince we can perform operation addfirst(ewith addbefore(first() )and...
20,968
first( ( ( addafter( , ( , next( ( ( , addbefore( , ( , , prev( ( ( , , addfirst( ( , , , last( ( ( , , , remove(first()
20,969
set( , ( , , addafter(first(), ( , , , the node list adtwith its built-in notion of positionis useful in number of settings for examplea program that simulates game of cards could model each person' hand as node list since most people keep cards of the same suit togetherinserting and removing cards from person' hand co...
20,970
adt java interface for the node list yet another deque adapter with respect to our discussion of the node list adtwe note that this adt is sufficient to define an adapter class for the deque adtas shown in table table node list realization of deque by means of
20,971
realization with node-list methods size()isempty(size()isempty(getfirst(first()*element(getlast(last()*element(addfirst(eaddfirst(eaddlast(eaddlast(eremovefirst(remove(first()removelast(remove(last()doubly linked list implementation suppose we would like to implement the node list adt using doubly linked list (section ...
20,972
linked list implementing the position adt this class is similar to class dnode shown in code fragment except that now our nodes store generic element instead of character string note that the prev and next instance variables in the dnode class below are private references to other dnode objects code fragment class dnod...
20,973
next and prev references of ' two new neighbors this method is given in code fragment and is illustrated (againin figure recalling the use of sentinels (section )note that this algorithm works even if is the last real position code fragment inserting an element after position in linked list figure adding anew node afte...
20,974
position similar to the discussion in section to perform this operationwe link the two neighbors of to refer to one another as new neighbors--linking out note that after is linked outno nodes will be pointing to phencethe garbage collector can reclaim the space for this algorithm is given in code fragment and is illust...
20,975
adt in ( time thusa doubly linked list is an efficient implementation of the list adt node list implementation in java portions of the java class nodepositionlistwhich implements the node list adt using doubly linked listare shown in code fragments code fragment shows nodeposition list' instance variablesits constructo...
20,976
nodepositionlist class implementing the node list adt with doubly linked list (continued from code fragment continues in code fragment
20,977
nodepositionlist class implementing the node list adt with doubly linked list (continued from code fragments and note that the mechanism used to invalidate position in the remove method is
20,978
checkposition convenience function iterators typical computation on an array listlistor sequence is to march through its elements in orderone at timefor exampleto look for specific element the iterator and iterable abstract data types
20,979
through collection of elements one element at time an iterator consists of sequence sa current element in sand way of stepping to the next element in and making it the current element thusan iterator extends the concept of the position adt we introduced in section in facta position can be thought of as an iterator that...
20,980
make it simple for us to specify computations that need to loop through the elements of list to guarantee that node list supports the above methodsfor examplewe could add this method to the position list interfaceas shown in code fragment in this casewe would also want to state that position list extends iterable there...
20,981
constructjava provides shorthand notation for such loopscalled the for-each loop the syntax for such loop is as followsfor (type name expressionloop statement where expression evaluates to collection that implements the java lang iterable interfacetype is the type of object returned by the iterator for this classand na...
20,982
for (int vtotal +iimplementing iterators one way to implement an iterator for collection of elements is to make "snapshotof it and iterate over that this approach would involve storing the collection in separate data structure that supports sequential access to its elements for examplewe could insert all the elements o...
20,983
the iterator(method of class nodepositionlist position iterators for adts that support the notion of positionsuch as the list and sequence adtswe can also provide the following methodpositions()return an iterable object (like an array list or node listcontaining the positions in the collection as elements an iterator r...
20,984
original list code fragment adding iterator methods to the position list interface code fragment the positions(method of class nodepositionlist the iterator(method returned by this and other iterable objects defines restricted type of iterator that allows only one pass through the elements more powerful iterators can a...
20,985
being located between two characters on screen specificallythe java util listiterator interface includes the following methodsadd( )add the element at the current position of the iterator hasnext()true if and only if there is an element after the current position of the iterator hasprevious()true if and only if there i...
20,986
to its iterator(method)java util iterator objects have "fail-fastfeature that immediately invalidates such an iterator if its underlying collection is modified unexpectedly for exampleif java util linkedlist object has returned five different iterators and one of them modifies lthen the other four all become immediatel...
20,987
isempty( ( time get(iget(ia is ( ) is (min{in }first(listiterator(first element is next last(listiterator(size()last element is previous prev(pprevious( ( time next(pnext( ( time set(peset(eo( time set( ,eset(iea is ( ) is (min{ , }add( ,
20,988
(ntime remove(iremove(ia is ( ) is (min{in }addfirst(eadd( ,ea is ( ), is ( addfirst(eaddfirst(eonly exists in lo( addlast(eadd(eo( time addlast(eaddlast(eonly exists in lo( addafter(peadd(einsertion is at cursora is ( ) is ( addbefore( ,eadd(einsertion is at cursora is ( ), is ( remove(premove(
20,989
list adts and the collections framework in this sectionwe discuss general list adtswhich combine methods of the dequearray listand/or node list adts before describing such adtswe mention larger context in which they exist the java collections framework java provides package of data structure interfaces and classeswhich...
20,990
include peek((same as front())offer( (same as enqueue( ))and poll((same as dequeue()setan interface extending collection to sets the java collections framework also includes several concrete classes implementing various combinations of the above interfaces rather than list each of these classes herehoweverwe discuss th...
20,991
search occurs when rn/ thusthe running time is still (noperations add( ,eand remove(ialso must perform link hopping to locate the node storing the element with index iand then insert or delete node the running times of these implementations of add( ,eand remove(iare likewise (min( - + ))which is (none advantage of this...
20,992
type )and adds two more methods implementing sequence with an array if we implement the sequence adt with doubly linked listwe would get similar performance to that of the java util linkedlist class so suppose instead we want to implement sequence by storing each element of in cell [iof an array we can define position ...
20,993
in this array implementation of sequencethe addfirstaddbeforeaddafterand remove methods take (ntimebecause we have to shift position objects to make room for the new position or to fill in the hole created by the removal of the old position (just as in the insert and remove methods based on indexall the other position-...
20,994
return an iterable collection of the most accessed elements using sorted list and nested class the first implementation of favorite list that we consider (in code fragments is to build classfavoriteliststoring references to accessed objects in linked list ordered by nonincreasing access counts this class also uses feat...
20,995
class favoritelistincluding nested classentryfor representing elements and their access count (continued from code fragment using list with the move-to-front heuristic
20,996
time proportional to the index of in the favorite list that isif is the kth most popular element in the favorite listthen accessing it takes (ktime in many reallife access sequencesincluding those formed by the visits that users make to web pagesit is common thatonce an element is accessedit is likely to be accessed ag...
20,997
move-to-front implementation has faster access times for this scenario this benefit comes at costhowever implementing the move-to-front heuristic in java in code fragment we give an implementation of favorite list using the move-to-front heuristic we implement the move-to-front approach in this case by defining new cla...
20,998
accessed in the simulation code fragment class favoritelistmtf implementing the move-to-front heuristic this class extends favoritelist (code fragments and overrides methods moveup and top
20,999
illustrating the use of the favoriteslist and favoritelistmtf classes for counting web page access counts this simulation randomly