id
int64
0
25.6k
text
stringlengths
0
4.59k
22,100
setsmultisetsand multimaps we conclude this by examining several additional abstractions that are closely related to the map adtand that can be implemented using data structures similar to those for map set is an unordered collection of elementswithout duplicatesthat typically supports efficient membership tests in ess...
22,101
in the next sectionwe will see that the above five methods suffice for deriving all other behaviors of set those remaining behaviors can be naturally grouped as follows we begin by describing the following additional operations for removing one or more elements from sets remove( )remove element from the set if the set ...
22,102
mapshash tablesand skip lists python' mutableset abstract base class to aid in the creation of user-defined set classespython' collections module provides mutableset abstract base class (just as it provides the mutablemapping abstract base class discussed in section the mutableset base class provides concrete implement...
22,103
supports syntax def or (selfother)"""return new set that is the union of two existing sets ""result type(self)create new instance of concrete class for in selfresult add(efor in otherresult add(ereturn result code fragment an implementation of the mutableset or methodwhich computes the union of two existing sets an imp...
22,104
implementing setsmultisetsand multimaps sets although sets and maps have very different public interfacesthey are really quite similar set is simply map in which keys do not have associated values any data structure used to implement map can be modified to implement the set adt with similar performance guarantees we co...
22,105
class multimap """ multimap class built upon use of an underlying map for storage ""maptype dict map typecan be redefined by subclass def init (self) """create new empty multimap instance ""create map instance for storage self map self maptype self def iter (self) """iterate through all ( ,vpairs in multimap "" for ,se...
22,106
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - give concrete implementation of the pop method in the context of the mutablemapping classrelying only on the five primary abstract methods of that class - give concrete implementation of the itemsmethod in the context o...
22,107
- what is the result of exercise - when collisions are handled by double hashing using the secondary hash function ( ( mod ) - what is the worst-case time for putting entries in an initially empty hash tablewith collisions resolved by chainingwhat is the best caser- show the result of rehashing the hash table shown in ...
22,108
- give pseudo-code description of the using skip list delitem map operation when - give concrete implementation of the pop methodin the context of mutableset abstract base classthat relies only on the five core set behaviors described in section - give concrete implementation of the isdisjoint method in the context of ...
22,109
- perform experiments on our chainhashmap and probehashmap classes to measure its efficiency using random key sets and varying limits on the load factor (see exercise - - our implementation of separate chaining in chainhashmap conserves memory by representing empty buckets in the table as nonerather than as empty insta...
22,110
mapshash tablesand skip lists - although keys in map are distinctthe binary search algorithm can be applied in more general setting in which an array stores possibly duplicative elements in nondecreasing order consider the goal of identifying the index of the leftmost element with key greater than or equal to given doe...
22,111
- python' collections module provides an ordereddict class that is unrelated to our sorted map abstraction an ordereddict is subclass of the standard hash-based dict class that retains the expected ( performance for the primary map operationsbut that also guarantees that the iter method reports items of the map accordi...
22,112
notes hashing is well-studied technique the reader interested in further study is encouraged to explore the book by knuth [ ]as well as the book by vitter and chen [ skip lists were introduced by pugh [ our analysis of skip lists is simplification of presentation given by motwani and raghavan [ for more in-depth analys...
22,113
search trees contents binary search trees navigating binary search tree searches insertions and deletions python implementation performance of binary search tree balanced search trees python framework for balancing search trees avl trees update operations python implementation splay trees splaying when to splay python ...
22,114
binary search trees in we introduced the tree data structure and demonstrated variety of applications one important use is as search tree (as described on page in this we use search tree structure to efficiently implement sorted map the three most fundamental methods of map (see section arem[ ]return the value associat...
22,115
navigating binary search tree we begin by demonstrating that binary search tree hierarchically represents the sorted order of its keys in particularthe structural property regarding the placement of keys within binary search tree assures the following important consequence regarding an inorder traversal (section of the...
22,116
search trees the "firstposition of binary search tree can be located by starting walk at the root and continuing to the left childas long as left child exists by symmetrythe last position is reached by repeated steps rightward starting at the root the successor of positionafter( )is determined by the following algorith...
22,117
searches the most important consequence of the structural property of binary search tree is its namesake search algorithm we can attempt to locate particular key in binary search tree by viewing it as decision tree (recall figure in this casethe question asked at each position is whether the desired key is less thanequ...
22,118
analysis of binary tree searching the analysis of the worst-case running time of searching in binary search tree is simple algorithm treesearch is recursive and executes constant number of primitive operations for each recursive call each recursive call of treesearch is made on child of the previous position that istre...
22,119
insertions and deletions algorithms for inserting or deleting entries of binary search tree are fairly straightforwardalthough not trivial insertion the map command [kvas supported by the setitem methodbegins with search for key (assuming the map is nonemptyif foundthat item' existing value is reassigned otherwisea nod...
22,120
deletion deleting an item from binary search tree is bit more complex than inserting new item because the location of the deletion might be anywhere in the tree (in contrastinsertions are always enacted at the bottom of path to delete an item with key kwe begin by calling treesearch(tt root)kto find the position of sto...
22,121
( (bfigure deletion from the binary search tree of figure bwhere the item to delete (with key is stored at position with one child (abefore the deletion(bafter the deletion (ap (bfigure deletion from the binary search tree of figure bwhere the item to delete (with key is stored at position with two childrenand replaced...
22,122
python implementation in code fragments through we define treemap class that implements the sorted map adt using binary search tree in factour implementation is more general we support all of the standard map operations (section )all additional sorted map operations (section )and positional operations including first)l...
22,123
class treemap(linkedbinarytreemapbase) """sorted map implementation using binary search tree "" override position class class position(linkedbinarytree position) def key(self) """return key of map key-value pair "" return self elementkey def value(self) """return value of map key-value pair "" return self elementvalue ...
22,124
def first(self)"""return the first position in the tree (or none if empty""return self subtree first position(self root)if len(self else none def last(self)"""return the last position in the tree (or none if empty""return self subtree last position(self root)if len(self else none def before(selfp)"""return the position...
22,125
def find min(self)"""return (key,valuepair with minimum key (or none if empty""if self is empty)return none elsep self firstreturn ( key) value)def find ge(selfk)"""return (key,valuepair with least key greater than or equal to return none if there does not exist such key ""if self is empty)return none elsemay not find ...
22,126
def getitem (selfk)"""return value associated with key (raise keyerror if not found""if self is empty)raise keyerrorkey errorrepr( )elsep self subtree search(self root)khook for balanced tree subclasses self rebalance access(pif ! key)raise keyerrorkey errorrepr( )return valuedef setitem (selfkv)"""assign value to key ...
22,127
def delete(selfp)"""remove the item at given position ""inherited from linkedbinarytree self validate(pif self left(pand self right( ) has two children replacement self subtree last position(self left( )from linkedbinarytree self replace(preplacement element) replacement now has at most one child parent self parent(pin...
22,128
operation in [ ] [kv delete( )del [kt find position(kt first) last) find min) find maxt before( ) after(pt find lt( ) find le( ) find gt( ) find ge(kt find range(startstopiter( )reversed(trunning time (ho(ho(ho(ho(ho(ho(ho( ho(ntable worst-case running times of the operations for treemap we denote the current height of...
22,129
balanced search trees in the closing of the previous sectionwe noted that if we could assume random series of insertions and removalsthe standard binary search tree supports (log nexpected running times for the basic map operations howeverwe may only claim (nworst-case timebecause some sequences of operations may lead ...
22,130
search trees in the context of tree-balancing algorithma rotation allows the shape of tree to be modified while maintaining the search tree property if used wiselythis operation can be performed to avoid highly unbalanced tree configurations for examplea rightward rotation from the first formation of figure to the seco...
22,131
= = single rotation = = = = (ac= = single rotation = = = = (ba= = double rotation = = = = (cc= = double rotation = = = = (dfigure schematic illustration of trinode restructuring operation( and brequire single rotation( and drequire double rotation
22,132
python framework for balancing search trees our treemap classintroduced in section is concrete map implementation that does not perform any explicit balancing operations howeverwe designed that class to also serve as base class for other subclasses that implement more advanced tree-balancing algorithms summary of our i...
22,133
def rebalance insert(selfp)pass def rebalance delete(selfp)pass def rebalance access(selfp)pass code fragment additional code for the treemap class (continued from code fragment )providing stubs for the rebalancing hooks nonpublic methods for rotating and restructuring second form of support for balanced search trees i...
22,134
def relink(selfparentchildmake left child)"""relink parent node with child node (we allow child to be none""make it left child if make left childparent left child elsemake it right child parent right child if child is not nonemake child point to parent child parent parent def rotate(selfp)"""rotate position above its p...
22,135
avl trees the treemap classwhich uses standard binary search tree as its data structureshould be an efficient map data structurebut its worst-case performance for the various operations is linear timebecause it is possible that series of operations results in tree with linear height in this sectionwe describe simple ba...
22,136
an immediate consequence of the height-balance property is that subtree of an avl tree is itself an avl tree the height-balance property has also the important consequence of keeping the height smallas shown in the following proposition proposition the height of an avl tree storing entries is (log njustificationinstead...
22,137
by substituting the above value of in formula we obtainfor > - + * - ( > - ( > - ( by taking logarithms of both sides of formula we obtain log( ( ) from which we get log( ( ) ( which implies that an avl tree storing entries has height at most logn by proposition and the analysis of binary search trees given in section...
22,138
( (bfigure an example insertion of an item with key in the avl tree of figure (aafter adding new node for key the nodes storing keys and become unbalanced(ba trinode restructuring restores the height-balance property we show the heights of nodes above themand we identify the nodes xyand and subtrees and participating i...
22,139
+ + - - (ah+ + + - (bh+ + + - (cfigure rebalancing of subtree during typical insertion into an avl tree(abefore the insertion(bafter an insertion in subtree causes imbalance at (cafter restoring balance with trinode restructuring notice that the overall height of the subtree after the insertion is the same as before th...
22,140
deletion recall that deletion from regular binary search tree results in the structural removal of node having either zero or one children such change may violate the height-balance property in an avl tree in particularif position represents the parent of the removed node in tree there may be an unbalanced node on the ...
22,141
performance of avl trees by proposition the height of an avl tree with items is guaranteed to be (log nbecause the standard binary search tree operation had running times bounded by the height (see table )and because the additional work in maintaining balance factors and restructuring an avl tree can be bounded by the ...
22,142
python implementation complete implementation of an avltreemap class is provided in code fragments and it inherits from the standard treemap class and relies on the balancing framework described in section we highlight two important aspects of our implementation firstthe avltreemap overrides the definition of the neste...
22,143
positional-based utility methods def recompute height(selfp) node height max( node left height) node right height)def isbalanced(selfp)return abs( node left heightp node right height)< def tall child(selfpfavorleft=false)parameter controls tiebreaker if node left height( if favorleft else node right height)return self ...
22,144
splay trees the next search tree structure we study is known as splay tree this structure is conceptually quite different from the other balanced search trees we discuss in this for splay tree does not strictly enforce logarithmic upper bound on the height of the tree in factthere are no additional heightbalanceor othe...
22,145
zig-zagone of and is left child and the other is right child (see figure in this casewe promote by making have and as its childrenwhile maintaining the inorder relationships of the nodes in (at (bfigure zig-zag(abefore(bafter there is another symmetric configuration where is right child and is left child zigx does not ...
22,146
( ( (cfigure example of splaying node(asplaying the node storing starts with zig-zag(bafter the zig-zag(cthe next step will be zig-zig (continues in figure
22,147
( ( ( figure example of splaying node:(dafter the zig-zig(ethe next step is again zig-zig( after the zig-zig (continued from figure
22,148
when to splay the rules that dictate when splaying is performed are as followswhen searching for key kif is found at position pwe splay pelse we splay the leaf position at which the search terminates unsuccessfully for examplethe splaying in figures and would be performed after searching successfully for key or unsucce...
22,149
when deleting key kwe splay the position that is the parent of the removed noderecall that by the removal algorithm for binary search treesthe removed node may be that originally containing kor descendant node with replacement key an example of splaying following deletion is shown in figure ( ( ( ( (efigure deletion fr...
22,150
python implementation although the mathematical analysis of splay tree' performance is complex (see section )the implementation of splay trees is rather simple adaptation to standard binary search tree code fragment provides complete implementation of splaytreemap classbased upon the underlying treemap class and use of...
22,151
amortized analysis of splaying after zig-zig or zig-zagthe depth of position decreases by twoand after zig the depth of decreases by one thusif has depth dsplaying consists of sequence of  / zig-zigs and/or zig-zagsplus one final zig if is odd since single zig-zigzig-zagor zig affects constant number of nodesit can be...
22,152
an accounting analysis of splaying when we perform splayingwe pay certain number of cyber-dollars (the exact value of the payment will be determined at the end of our analysiswe distinguish three casesif the payment is equal to the splaying workthen we use it all to pay for the splaying if the payment is greater than t...
22,153
proposition let be the variation of ( caused by single splaying substep ( zigzig-zigor zig-zagfor node in we have the followingd < ( (xr( ) if the substep is zig-zig or zig-zag < ( (xr( )if the substep is zig justificationwe use the fact (see proposition appendix athatif and blog log log ( let us consider the change in...
22,154
proposition let be splay tree with root and let be the total variation of ( caused by splaying node at depth we have < ( (tr( ) justificationsplaying node consists of / splaying substepseach of which is zig-zig or zig-zagexcept possibly the last onewhich is zig if is odd let (xr(xbe the initial rank of xand for clet ri...
22,155
when deleting node from splay tree with keysthe ranks of all the ancestors of are decreased thusthe total variation of ( caused by the deletion is negativeand we do not need to make any payment to maintain the invariant when node is deleted thereforewe may summarize our amortized analysis in the following proposition (...
22,156
( , trees in this sectionwe consider data structure known as ( , tree it is particular example of more general structure known as multiway search treein which internal nodes may have more than two children other forms of multiway search trees will be discussed in section multiway search trees recall that general trees ...
22,157
( ( (cfigure (aa multiway search tree (bsearch path in for key (unsuccessful search)(csearch path in for key (successful search
22,158
searching in multiway tree searching for an item with key in multiway search tree is simple we perform such search by tracing path in starting at the root (see figure and when we are at -node during this searchwe compare the key with the keys kd- stored at if ki for some ithe search is successfully completed otherwisew...
22,159
( , )-tree operations multiway search tree that keeps the secondary data structures stored at each node small and also keeps the primary multiway tree balanced is the ( treewhich is sometimes called - tree or tree this data structure achieves these goals by maintaining two simple properties (see figure )size propertyev...
22,160
of ( treewe must have at least nodes at depth at least nodes at depth and so on thusthe number of external nodes in is at least in additionby proposition the number of external nodes in is thereforewe obtain < < taking the logarithm in base of the terms for the above inequalitieswe get that <log( < hwhich justifies our...
22,161
(au ww (bc (cfigure node split(aoverflow at -node (bthe third key of inserted into the parent of (cnode replaced with -node and -node ( ( ( ( ( ( figure an insertion in ( tree that causes cascading split(abefore the insertion(binsertion of causing an overflow(ca split(dafter the split new overflow occurs(eanother spli...
22,162
( ( ( ( ( ( ( ( ( ( ( (lfigure sequence of insertions into ( tree(ainitial tree with one item(binsertion of (cinsertion of (dinsertion of which causes an overflow(esplitwhich causes the creation of new root node( after the split(ginsertion of (hinsertion of which causes an overflow(isplit(jafter the split(kinsertion of...
22,163
analysis of insertion in ( , tree because dmax is at most the original search for the placement of new key uses ( time at each leveland thus (log ntime overallsince the height of the tree is (log nby proposition the modifications to single node to insert new key and child can be implemented to run in ( timeas can singl...
22,164
( ( ( ( ( ( ( (hfigure sequence of removals from ( tree(aremoval of causing an underflow(ba transfer operation(cafter the transfer operation(dremoval of causing an underflow(ea fusion operation( after the fusion operation(gremoval of (hafter removing
22,165
fusion operation at node may cause new underflow to occur at the parent of wwhich in turn triggers transfer or fusion at (see figure hencethe number of fusion operations is bounded by the height of the treewhich is (log nby proposition if an underflow propagates all the way up to the rootthen the root is simply deleted...
22,166
red-black trees although avl trees and ( trees have number of nice propertiesthey also have some disadvantages for instanceavl trees may require many restructure operations (rotationsto be performed after deletionand ( trees may require many split or fusing operations to be performed after an insertion or removal the d...
22,167
figure an illustration that the red-black tree of figure corresponds to the ( tree of figure based on the highlighted grouping of red nodes with their black parents if is -nodethen keep the (blackchildren of as is if is -nodethen create new red node ygive ' last two (blackchildren to yand make the first child of and be...
22,168
justificationlet be red-black tree storing entriesand let be the height of we justify this proposition by establishing the following factlog( < < log( let be the common black depth of all nodes of having zero or one children let be the ( tree associated with and let be the height of (excluding trivial leavesbecause of ...
22,169
case the sibling of is black (or none(see figure in this casethe double red denotes the fact that we have added the new node to corresponding -node of the ( tree effectively creating malformed -node this formation has one red node (ythat is the parent of another red node ( )while we want it to have the two red nodes as...
22,170
case the sibling of is red (see figure in this casethe double red denotes an overflow in the corresponding ( tree to fix the problemwe perform the equivalent of split operation namelywe do recoloringwe color and black and their parent red (unless is the rootin which caseit remains blacknotice that unless is the rootthe...
22,171
( ( ( ( ( ( ( ( ( ( ( (lfigure sequence of insertions in red-black tree(ainitial tree(binsertion of (cinsertion of which causes double red(dafter restructuring(einsertion of which causes double red( after recoloring (the root remains black)(ginsertion of (hinsertion of (iinsertion of which causes double red(jafter rest...
22,172
( ( ( ( (qfigure sequence of insertions in red-black tree(minsertion of which causes double red(nafter restructuring(oinsertion of which causes double red(pafter recoloring there is again double redto be handled by restructuring(qafter restructuring (continued from figure
22,173
deletion deleting an item with key from red-black tree initially proceeds as for binary search tree (section structurallythe process results in the removal node that has at most one child (either that originally containing key or its inorder predecessorand the promotion of its remaining child (if anyif the removed node...
22,174
we consider three possible cases to remedy deficit case node is black and has red child (see figure we perform trinode restructuringas originally described in section the operation restructure(xtakes the node xits parent yand grandparent zlabels them temporarily left to right as aband cand replaces with the node labele...
22,175
case node is black and both children of are black (or noneresolving this case corresponds to fusion operation in the corresponding ( tree as must represent -node we do recoloringwe color redandif is redwe color it black (see figure this does not introduce any red violationbecause does not have red child in the case tha...
22,176
case node is red (see figure because is red and theavy has black depth at least must be black and the two subtrees of must each have black root and black depth equal to that of theavy in this casewe perform rotation about and zand then recolor black and red this denotes reorientation of -node in the corresponding ( tre...
22,177
( ( ( ( ( ( ( ( ( ( (kfigure sequence of deletions from red-black tree(ainitial tree(bremoval of (cremoval of causing black deficit to the right of (handled by restructuring)(dafter restructuring(eremoval of ( removal of causing black deficit to the right of (handled by recoloring)(gafter recoloring(hremoval of (iremov...
22,178
performance of red-black trees the asymptotic performance of red-black tree is identical to that of an avl tree or ( tree in terms of the sorted map adtwith guaranteed logarithmic time bounds for most operations (see table for summary of the avl performance the primary advantage of red-black tree is that an insertion o...
22,179
python implementation complete implementation of redblacktreemap class is provided in code fragments through it inherits from the standard treemap class and relies on the balancing framework described in section we beginin code fragment by overriding the definition of the nested node class to introduce an additional bo...
22,180
positional-based utility methods we consider nonexistent child to be trivially black def set red(selfp) node red true def set black(selfp) node red false def set color(selfpmake red) node red make red def is red(selfp)return is not none and node red def is red leaf(selfp)return self is red(pand self is leaf(pdef get re...
22,181
support for deletions def rebalance delete(selfp)if len(self= special caseensure that root is black self set black(self root)elif is not nonen self num children(pif = deficit exists unless child is red leaf next(self children( )if not self is red leaf( )self fix deficit(pcelif = removed black node with red child if sel...
22,182
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - if we insert the entries ( )( )( , )( )and ( )in this orderinto an initially empty binary search treewhat will it look liker- insertinto an empty binary search treeentries with keys (in this orderdraw the tree after eac...
22,183
- the rules for deletion in an avl tree specifically require that when the two subtrees of the node denoted as have equal heightchild should be chosen to be "alignedwith (so that and are both left children or both right childrento better understand this requirementrepeat exercise assuming we picked the misaligned choic...
22,184
- consider tree storing , entries what is the worst-case height of in the following casesa is binary search tree is an avl tree is splay tree is ( tree is red-black tree - draw an example of red-black tree that is not an avl tree - let be red-black tree and let be the position of the parent of the original node that is...
22,185
- describe how to perform an operation remove range(startstopthat removes all the items whose keys fall within range(startstopin sorted map that is implemented with binary search tree and show that this method runs in time ( )where is the number of items removed and is the height of - repeat the previous problem using ...
22,186
- if the approach described in the previous problem were implemented as part of the treemap classwhat additional modifications (if anywould be necessary to subclass such as avltreemap in order to maintain the efficiencyc- for standard binary search treetable claims ( )-time performance for the delete(pmethod explain wh...
22,187
- the standard splaying step requires two passesone downward pass to find the node to splayfollowed by an upward pass to splay the node describe method for splaying and searching for in one downward pass each substep now requires that you consider the next two nodes in the path down to xwith possible zig substep perfor...
22,188
- write python class that can take any red-black tree and convert it into its corresponding ( tree and can take any ( tree and convert it into its corresponding red-black tree - in describing multisets and multimaps in section we describe general approach for adapting traditional map by storing all duplicates within se...
22,189
notes some of the data structures discussed in this are extensively covered by knuth in his sorting and searching book [ ]and by mehlhorn in [ avl trees are due to adel'son-vel'skii and landis [ ]who invented this class of balanced search trees in binary search treesavl treesand hashing are described in knuth' sorting ...
22,190
sorting and selection contents why study sorting algorithms merge-sort divide-and-conquer array-based implementation of merge-sort the running time of merge-sort merge-sort and recurrence equations alternative implementations of merge-sort quick-sort randomized quick-sort additional optimizations for quick-sort studyin...
22,191
why study sorting algorithmsmuch of this focuses on algorithms for sorting collection of objects given collectionthe goal is to rearrange the elements so that they are ordered from smallest to largest (or to produce new copy of the sequence with such an orderas we did when studying priority queues (see section )we assu...
22,192
merge-sort divide-and-conquer the first two algorithms we describe in this merge-sort and quick-sortuse recursion in an algorithmic design pattern called divide-and-conquer we have already seen the power of recursion in describing algorithms in an elegant manner (see the divide-and-conquer pattern consists of the follo...
22,193
we can visualize an execution of the merge-sort algorithm by means of binary tree called the merge-sort tree each node of represents recursive invocation (or callof the merge-sort algorithm we associate with each node of the sequence that is processed by the invocation associated with the children of node are associate...
22,194
( ( ( ( ( ( figure visualization of an execution of merge-sort each node of the tree represents recursive call of merge-sort the nodes drawn with dashed lines represent calls that have not been made yet the node drawn with thick lines represents the current call the empty nodes drawn with thin lines represent completed...
22,195
( ( ( ( ( (lfigure visualization of an execution of merge-sort (combined with figures and
22,196
( ( ( (pfigure visualization of an execution of merge-sort (continued from figure several invocations are omitted between (mand (nnote the merging of two halves performed in step (pproposition the merge-sort tree associated with an execution of mergesort on sequence of size has height log nwe leave the justification of...
22,197
array-based implementation of merge-sort we begin by focusing on the case when sequence of items is represented as an (array-basedpython list the merge function (code fragment is responsible for the subtask of merging two previously sorted sequencess and with the output copied into we copy one element during each pass ...
22,198
sorting and selection def merge sort( ) """sort the elements of python list using the merge-sort algorithm "" len( if return list is already sorted divide mid / [ :midcopy of first half [mid:ncopy of second half conquer (with recursionsort copy of first half merge sort( sort copy of second half merge sort( merge result...
22,199
merge-sort tree as portrayed in figures through can guide our analysis consider recursive call associated with node of the merge-sort tree the divide step at node is straightforwardthis step runs in time proportional to the size of the sequence for vbased on the use of slicing to create copies of the two list halves we...