id
int64
0
25.6k
text
stringlengths
0
4.59k
20,200
chap listsstacksand queues / simple payroll entry with idnameaddress fields class payroll private integer idprivate string nameprivate string address/constructor payroll(int inidstring innamestring inaddrid inidname innameaddress inaddr/data member access functions public integer getid(return idpublic string getname(re...
20,201
/container for key-value pair class kvpair private key kprivate /constructors kvpair( nulle nullkvpair(key kvale evalk kvale eval/data member access functions public key key(return kpublic value(return efigure implementation for class representing key-value pair need some mechanism for extracting keys that is sufficien...
20,202
chap listsstacksand queues space overhead will not be great simple class for representing key-value pairs is shown in figure the insert method of the dictionary class supports the key-value pair implementation because it takes two parametersa record and its associated key for that dictionary now that we have defined th...
20,203
sec dictionaries /*dictionary implemented by unsorted array-based list *class ualdictionary implements dictionary private static final int defaultsize /default size private alistlist/to store dictionary /constructors ualdictionary(this(defaultsize)ualdictionary(int szlist new alist>(sz)public void clear(list clear()/re...
20,204
chap listsstacksand queues public int size(/return list size return list length()figure (continuedfind the record prior to removalwe would still need to shift down the remaining records in the list to fill the gap left by the remove operation given two keyswe have not properly addressed the issue of how to compare them...
20,205
sec further reading further reading for more discussion on choice of functions used to define the list adtsee the work of the reusable software research group from ohio state their definition for the list adt can be found in [swh more information about designing such classes can be found in [sw exercises assume list ha...
20,206
chap listsstacksand queues in the linked list implementation presented in section the current position is implemented using pointer to the element ahead of the logical current node the more "naturalapproach might seem to be to have curr point directly to the node containing the current element howeverif this was doneth...
20,207
sec exercises (athe data field is eight bytesa pointer is four bytesand the array holds twenty elements (bthe data field is two bytesa pointer is four bytesand the array holds thirty elements (cthe data field is one bytea pointer is four bytesand the array holds thirty elements (dthe data field is bytesa pointer is fou...
20,208
chap listsstacksand queues common problem for compilers and text editors is to determine if the parentheses (or other bracketsin string are balanced and properly nested for examplethe string "((())())()contains properly nested pairs of parenthesesbut the string ")()(does notand the string "())does not contain properly ...
20,209
use singly linked lists to implement integers of unlimited size each node of the list should store one digit of the integer you should implement additionsubtractionmultiplicationand exponentiation operations limit exponents to be positive integers what is the asymptotic running time for each of your operationsexpressed...
20,210
chap listsstacksand queues top ' ' ' ' ' ' ' ' figure an array-based stack storing variable-length strings each position stores either one character or the length of the string immediately to the left of it in the stack define an adt for bag (see section and create an array-based implementation for bags be sure that yo...
20,211
binary trees the list representations of have fundamental limitationeither search or insert can be made efficientbut not both at the same time tree structures permit both efficient access and update to large collections of data binary trees in particular are widely used and relatively easy to implement but binary trees...
20,212
chap binary trees figure an example binary tree node is the root nodes and are ' children nodes and together form subtree node has two childrenits left child is the empty tree and its right child is nodes acand are ancestors of nodes deand make up level of the treenode is at level the edges from to to to form path of l...
20,213
sec definitions and properties ( (ba empty (cempty (dfigure two different binary trees (aa binary tree whose root has nonempty left child (ba binary tree whose root has non-empty right child (cthe binary tree of (awith the missing right child made explicit (dthe binary tree of (bwith the missing left child made explici...
20,214
chap binary trees any number of internal nodes figure tree containing internal nodes and single leaf the full binary tree theorem some binary tree implementations store data only at the leaf nodesusing the internal nodes to provide structure to the tree more generallybinary tree implementations might require some amoun...
20,215
induction stepgiven tree with internal nodesselect an internal node whose children are both leaf nodes remove both of ' childrenmaking leaf node call the new tree has internal nodes from the induction hypothesist has leaves nowrestore ' two children we once again have tree with internal nodes how many leaves does haveb...
20,216
chap binary trees /*adt for binary tree nodes *public interface binnode /*return and set the element value *public element()public void setelement( )/*return the left child *public binnode left()/*return the right child *public binnode right()/*return true if this is leaf node *public boolean isleaf()figure binary tree...
20,217
sec binary tree traversals must be visited in an order that preserves some relationship for examplewe might wish to make sure that we visit any given node before we visit its children this is called preorder traversal example the preorder enumeration for the tree of figure is abdcegfhi the first node printed is the roo...
20,218
chap binary trees function preorder first checks that the tree is not empty (if it isthen the traversal is done and preorder simply returnsotherwisepreorder makes call to visitwhich processes the root node ( prints the value or performs some computation as required by the applicationfunction preorder is then called rec...
20,219
is being traversed by using the first designwhich explicitly supports processing of empty subtreesthe problem is avoided another issue to consider when designing traversal is how to define the visitor function that is to be executed on every node one approach is simply to write new version of the traversal for each suc...
20,220
chap binary trees to figure to be binary search treethe left child of the node with value must have value between and fall within given range of values fortunatelyit requires only simple local calculation to determine which child(rento visit more difficult situation is illustrated by the following problem given an arbi...
20,221
discussion on techniques for determining the space requirements for given binary tree node implementation the section concludes with an introduction to the arraybased implementation for complete binary trees pointer-based node implementations by definitionall binary tree nodes have two childrenthough one or both childr...
20,222
chap binary trees /*binary tree node implementationpointers to children *class bstnode implements binnode private key key/key for this node private element/element for this node private bstnode left/pointer to left child private bstnode right/pointer to right child /*constructors *public bstnode({left right nullpublic ...
20,223
sec binary tree node implementations figure illustration of typical pointer-based binary tree implementationwhere each node stores two child pointers and value figure an expression tree for ( ac larger to handle the wider range of possible values at the same timeleaf nodes need not store child pointers java allows us t...
20,224
chap binary trees public interface varbinnode public boolean isleaf()class varleafnode implements varbinnode /leaf node private string operand/operand value public varleafnode(string valoperand valpublic boolean isleaf(return truepublic string value(return operand}/*internal node *class varintlnode implements varbinnod...
20,225
figure presents sample node implementation it includes two classes derived from class varbinnodenamed leafnode and intlnode class intlnode accesses its children through pointers of type varbinnode function traverse illustrates the use of these classes when traverse calls method isleafjava' runtime environment determine...
20,226
chap binary trees public interface varbinnode public boolean isleaf()public void traverse()class varleafnode implements varbinnode /leaf node private string operand/operand value public varleafnode(string valoperand valpublic boolean isleaf(return truepublic string value(return operandpublic void traverse(visit visitle...
20,227
sec binary tree node implementations hidden from users of that tree class on the other handif the nodes are objects that have meaning to users of the tree separate from their existence as nodes in the treethen the version of figure might be preferred because hiding the internal behavior of the nodes becomes more import...
20,228
chap binary trees if dthe overhead drops to about one half of the total space howeverif only leaf nodes store useful informationthe overhead fraction for this implementation is actually three quarters of the total spacebecause half of the "dataspace is unused if full binary tree needs to store data only at the leaf nod...
20,229
this section presents simplecompact implementation for complete binary trees recall that complete binary trees have all levels except the bottom filled out completelyand the bottom level has all of its nodes filled in from left to right thusa complete binary tree of nodes has only one possible shape you might think tha...
20,230
chap binary trees (aposition parent left child right child left sibling right sibling (bfigure complete binary tree and its array implementation (athe complete binary tree with twelve nodes each node has been labeled with its position in the tree (bthe positions for the relatives of each node dash indicates that the re...
20,231
sec binary search trees ( (bfigure two binary search trees for collection of values tree (aresults if values are inserted in the order tree (bresults if the same values are inserted in the order figure shows class declaration for the bst that implements the dictionary adt the public member functions include those requi...
20,232
chap binary trees import java lang comparable/*binary search tree implementation for dictionary adt *class bsteimplements dictionary private bstnode root/root of the bst int nodecount/number of nodes in the bst /*constructor *bst(root nullnodecount /*reinitialize tree *public void clear(root nullnodecount /*insert reco...
20,233
sec binary search trees /*remove and return the root node from the dictionary @return the record removednull if tree is empty *public removeany(if (root !nulle temp root element()root removehelp(rootroot key())nodecount--return tempelse return null/*@return record with key value knull if none exist @param the key value...
20,234
chap binary trees figure an example of bst insertion record with value is inserted into the bst of figure (athe node with value becomes the parent of the new node containing you should pay careful attention to the implementation for inserthelp note that inserthelp returns pointer to bstnode what is being returned is su...
20,235
minimum key valuethuschanging the pointer as described will maintain bstwith removed the code for this methodnamed deleteminis as followsprivate bstnode deletemin(bstnode rtif (rt left(=nullreturn rt right()else rt setleft(deletemin(rt left()))return rtexample figure illustrates the deletemin process beginning at the r...
20,236
chap binary trees subroot figure an example of deleting the node with minimum value in this treethe node with minimum value is the left child of the root thusthe root' left pointer is changed to point to ' right child thusthe question becomeswhich value can substitute for the one being removedit cannot be any arbitrary...
20,237
sec binary search trees figure an example of removing the value from the bst the node containing this value has two children we replace value with the least value from the node' right subtreein this case /*remove node with key value @return the tree with the node removed *private bstnode removehelp(bstnode rtkey kif (r...
20,238
chap binary trees in the case when this node has two childrenthe depth of the node with smallest value in its right subtree thusin the worst casethe cost of any one of these operations is the depth of the deepest node in the tree this is why it is desirable to keep bsts balancedthat iswith least possible height if bina...
20,239
next job selected is the one with the highest priority priority is indicated by particular value associated with the job (and might change while the job remains in the wait listwhen collection of objects is organized by importance or prioritywe call this priority queue normal queue data structure will not implement pri...
20,240
chap binary trees min-heaps and max-heaps both have their uses for examplethe heapsort of section uses the max-heapwhile the replacement selection algorithm of section uses min-heap the examples in the rest of this section will use max-heap be careful not to confuse the logical representation of heap with its physical ...
20,241
import java lang comparable/*max-heap implementation *public class maxheapprivate [heap/pointer to the heap array private int size/maximum size of the heap private int /number of things in heap public maxheap( [hint numint maxheap hn numsize maxbuildheap()/*return current size of the heap *public int heapsize(return /*...
20,242
chap binary trees /*put element in its correct place *private void siftdown(int posassert (pos > &(pos "illegal heap position"while (!isleaf(pos)int leftchild(pos)if (( <( - )&(heap[jcompareto(heap[ + ] ) ++/ is now index of child with greater value if (heap[poscompareto(heap[ ]> returndsutil swap(heapposj)pos /move do...
20,243
sec heaps and priority queues routine is finished if the value of is greater than that of its parentthen the two elements swap positions from herethe process of comparing to its (currentparent continues until reaches its correct position each call to insert takes th(log ntime in the worst casebecause the value being in...
20,244
chap binary trees ( (bfigure two series of exchanges to build max-heap (athis heap is built by series of nine exchanges in the order ( - )( - )( - )( - )( - )( - )( - )( - )( - (bthis heap is built by series of four exchanges in the order ( - )( - )( - )( - figure final stage in the heap-building algorithm both subtree...
20,245
sec heaps and priority queues ( ( (cfigure the siftdown operation the subtrees of the root are assumed to be heaps (athe partially completed heap (bvalues and are swapped (cvalues and are swapped to form the final heap sum of total distances that elements can go is therefore log xn log = = - ( - from equation we know t...
20,246
chap binary trees when searching for an arbitrary valueit is only good for finding the maximum value howeverif we already know the index for an object within the heapit is simple matter to update its priority (including changing its position to maintain the heap propertyor remove it the remove method takes as input the...
20,247
sec huffman coding trees letter frequency letter frequency figure relative frequencies for the letters of the alphabet as they appear in selected set of english documents "frequencyrepresents the expected frequency of occurrence per lettersignoring case if some characters are used more frequently than othersis it possi...
20,248
chap binary trees letter frequency figure the relative frequencies for eight selected letters the weighted path length of leaf to be its weight times its depth the binary tree with minimum external path weight is the one with the minimum sum of weighted path lengths for the given set of leaves letter with high weight s...
20,249
sec huffman coding trees step step step step step figure the first five steps of the building process for sample huffman tree
20,250
chap binary trees figure huffman tree for the letters of figure and intlnode this implementation reflects the fact that leaf and internal nodes contain distinctly different information figure shows the implementation for the huffman tree nodes of the tree store key-value pairs (see figure )where the key is the weight a...
20,251
/*binary tree node implementation with just an element field (no keyand pointers to children *class huffnode implements binnode private element/element for this node private huffnode left/pointer to left child private huffnode right/pointer to right child /*constructors *public huffnode({left right nullpublic huffnode(...
20,252
chap binary trees class hufftree / huffman coding tree private huffnode root/root of the tree public hufftree(lettfreq valroot new huffnode(val)public hufftree(lettfreq valhufftree lhufftree rroot new huffnode(vall root() root())public huffnode root(return rootpublic int weight(/weight of tree is weight of root return ...
20,253
sec huffman coding trees /build huffman tree from list hufflist static hufftree buildtree(list hufflisthufftree tmp tmp tmp lettfreq tmpnodefor(hufflist movetopos( )hufflist length( hufflist movetopos( )/while at least two items left hufflist movetostart()tmp hufflist remove()tmp hufflist remove()tmpnode new lettfreq(t...
20,254
chap binary trees letter freq code bits figure the huffman codes for the letters of figure right branchesthen leftand finally one last right figure lists the codes for all eight letters given codes for the lettersit is simple matter to use these codes to encode text message we simply replace each letter in the string w...
20,255
set of codes is said to meet the prefix property if no code in the set is the prefix of another the prefix property guarantees that there will be no ambiguity in how bit string is decoded in other wordsonce we reach the last bit of code during the decoding processwe know which letter it is the code for huffman codes ce...
20,256
chap binary trees its occurring (pi )or cn pn this can be reorganized as cn fn ft where fi is the (relativefrequency of letter and ft is the total for all letter frequencies for this set of frequenciesthe expected cost per letter is [( )+( )+( )+( )+( )]/ / fixed-length code for these eight characters would require log...
20,257
many techniques exist for maintaining reasonably balanced bsts in the face of an unfriendly series of insert and delete operations one example is the avl tree of adelson-velskii and landiswhich is discussed by knuth [knu the avl tree (see section is actually bst whose insert and delete routines reorganize the tree stru...
20,258
chap binary trees prints the rootthen all nodes of level then all nodes of level and so on hintpreorder traversals make use of stack through recursive calls consider making use of another data structure to help implement the levelorder traversal write recursive function that returns the height of binary tree write recu...
20,259
sec exercises write recursive function named smallcount thatgiven the pointer to the root of bst and key kreturns the number of nodes having key values less than or equal to function smallcount should visit as few nodes in the bst as possible write recursive function named printrange thatgiven the pointer to the root o...
20,260
chap binary trees what will the huffman coding tree look like for set of sixteen characters all with equal weightwhat is the average code length for letter in this casehow does this differ from the smallest possible fixed length code for sixteen characters set of characters with varying weights is assigned huffman code...
20,261
(dthe records arrive with values having uniform random distribution (so the bst is likely to be well balanced insertions are performedfollowed by , , searches projects re-implement the composite design for the binary tree node class of figure using flyweight in place of null pointers to empty nodes one way to deal with...
20,262
chap binary trees implement priority queue class based on the max-heap class implementation of figure the following methods should be supported for manipulating the priority queuevoid enqueue(int objectidint priority)int dequeue()void changeweight(int objectidint newpriority)method enqueue inserts new object into the p...
20,263
non-binary trees many organizations are hierarchical in naturesuch as the military and most businesses consider company with president and some number of vice presidents who report to the president each vice president has some number of direct subordinatesand so on if we wanted to model this company with data structure...
20,264
chap non-binary trees root ancestors of parent of siblings of subtree rooted at children of figure notation for general trees node is the parent of nodes vs and thusvs and are children of nodes and are ancestors of nodes vs and are called siblings the oval surrounds the subtree having as its root into > disjoint subset...
20,265
/*general tree adt *interface gentree public void clear()/clear the tree public gtnode root()/return the root /make the tree have new rootgive first child and sib public void newroot( valuegtnode firstgtnode sib)public void newleftchild( value)/add left child figure the general tree node and general tree classes access...
20,266
chap non-binary trees figure an example of general tree example preorder traversal of the tree in figure visits the nodes in order racdebf postorder traversal of this tree visits the nodes in order cdeaf br to perform preorder traversalit is necessary to visit each of the children for given node (say rfrom left to righ...
20,267
clearly this implementation is not general purposebecause it is inadequate for such important operations as finding the leftmost child or the right sibling for node thusit may seem to be poor idea to implement general tree in this way howeverthe parent pointer implementation stores precisely the information required to...
20,268
chap non-binary trees objects are in different setsand function union merges two sets together private function find is used to find the ultimate root for an object an application using the union/find operations should store set of objectswhere each object is assigned unique index in the range to the indices refer to t...
20,269
sec the parent pointer implementation /*general tree class implementation for union/find *class parptrtree private integer [array/node array public parptrtree(int sizearray new integer[size]for (int = <sizei++array[inull/create node array /*determine if nodes are in different trees *public boolean differ(int aint binte...
20,270
chap non-binary trees parent' index node index label figure the parent pointer array implementation each node corresponds to position in the node array stores its value and pointer to its parent the parent pointers are represented by the position in the array of the parent the root of any tree stores rootrepresented gr...
20,271
sec the parent pointer implementation ( ( ( (dfigure an example of equivalence processing (ainitial configuration for the ten nodes of the graph in figure the nodes are placed into ten independent equivalence classes (bthe result of processing five edges(ab)(ch)(gf)(de)and (if(cthe result of processing two more edges(h...
20,272
chap non-binary trees using the parent pointer array representation nowconsider what happens when equivalence relationship (abis processed the root of the tree containing is aand the root of the tree containing is to make them equivalentone of these two nodes is set to be the parent of the other in this case it is irre...
20,273
as to which node is set to be the root for the combined tree in the case of equivalence pair (eg)the root of is while the root of is because is the root of the larger treenode is set to point to not all equivalences will combine two trees if edge (fgis processed when the representation is in the state shown in figure (...
20,274
chap non-binary trees figure an example of path compressionshowing the result of processing equivalence pair (heon the representation of figure (cunion rule for joining setsis th( lognthe notation "lognmeans the number of times that the log of must be taken before < for examplelog is because log log log and finally log...
20,275
sec general tree implementations index val par figure the "list of childrenimplementation for general trees the column of numbers to the left of the node array labels the array indices the column labeled "valstores node values the column labeled "parstores pointers to the parents for claritythese pointers are shown as ...
20,276
chap non-binary trees left val par right figure the "left-child/right-siblingimplementation adding tree as subtree of node is done by simply adding the root of to ' list of children the left-child/right-sibling implementation with the "list of childrenimplementationit is difficult to access node' right sibling figure p...
20,277
sec general tree implementations left val par right figure combining two trees that use the "left-child/right-siblingimplementation the subtree rooted at in figure now becomes the first child of three pointers are adjusted in the node arraythe left-child field of now points to node rwhile the right-sibling field for po...
20,278
chap non-binary trees val size (af (bfigure dynamic general tree representation with fixed-size arrays for the child pointers (athe general tree (bthe tree representation for each nodethe first field stores the node value while the second field stores the size of the child pointer array spaceand the old space is then r...
20,279
(ac (bfigure dynamic general tree representation with linked lists of child pointers (athe general tree (bthe tree representation root ( (bfigure converting from forest of general trees to single binary tree each node stores pointers to its left child and right sibling the tree roots are assumed to be siblings for the ...
20,280
chap non-binary trees (af (bfigure general tree converted to the dynamic "left-child/right-siblingrepresentation compared to the representation of figure this representation requires less space ( (bfigure full and complete -ary trees (athis tree is full (but not complete(bthis tree is complete (but not fullexample of -...
20,281
nodes in -ary tree can be derived we can also store complete -ary tree in an arraysimilar to the approach shown in section sequential tree implementations next we consider fundamentally different approach to implementing trees the goal is to store series of node values with the minimum information needed to reconstruct...
20,282
chap non-binary trees figure sample binary tree for sequential tree implementation examples example for the binary tree of figure the corresponding sequential representation would be as follows (assuming that '/stands for null)ab/ //ceg///fh// /( to reconstruct the tree structure from this node listwe begin by setting ...
20,283
sec sequential tree implementations two children (which may be subtreesimmediately follow in the node list if is leaf nodethen the next node in the list is the right child of some ancestor of xnot the right child of in particularthe next node will be the child of ' most recent ancestor that has not yet seen its right c...
20,284
chap non-binary trees will use the ")symbolto indicate the end of child list all leaf nodes are followed by ")symbol because they have no children leaf node that is also the last child for its parent would indicate this by two or more successive ")symbols example for the general tree of figure we get the sequential rep...
20,285
write an algorithm to determine if two binary trees are identical when the ordering of the subtrees for node is ignored for exampleif tree has root node with value rleft child with value and right child with value bthis would be considered identical to another tree with root node value rleft child value band right chil...
20,286
chap non-binary trees devise series of equivalence statements for collection of sixteen items that yields tree of height when both the weighted union rule and path compression are used what is the total number of parent pointers followed to perform this series one alternative to path compression that gives similar perf...
20,287
sec exercises figure sample tree for exercise draw the binary tree representing the following sequential representation for binary trees illustrated by example abd// // / / draw the binary tree representing the following sequential representation for binary trees illustrated by example / / / show the bit vector for lea...
20,288
chap non-binary trees projects write classes that implement the general tree class declarations of figure using the dynamic "left-child/right-siblingrepresentation described in section write classes that implement the general tree class declarations of figure using the linked general tree implementation with child poin...
20,289
proved performance you should compare the following four implementations(astandard union/find with path compression and weighted union (bpath compression and weighted unionexcept that path compression is done after the unioninstead of during the find operation that ismake all nodes along the paths traversed in both tre...
20,290
sorting and searching
20,291
internal sorting we sort many things in our everyday livesa handful of cards when playing bridgebills and other piles of paperjars of spicesand so on and we have many intuitive strategies that we can use to do the sortingdepending on how many objects we have to sort and how hard they are to move around sorting is also ...
20,292
chap internal sorting and quicksortby taking advantage of the best case behavior of another algorithm (insertion sortwe'll see several examples of how we can tune an algorithm for better performance we'll see that special case behavior by some algorithms makes them the best solution for special niche applications (heap...
20,293
algorithm is said to be stable if it does not change the relative ordering of records with identical key values manybut not allof the sorting algorithms presented in this are stableor can be made stable with minor changes when comparing two sorting algorithmsthe most straightforward approach would seem to be simply pro...
20,294
chap internal sorting = figure an illustration of insertion sort each column shows the array after the iteration with the indicated value of in the outer for loop values above the line in each column have been sorted arrows indicate the upward motions of records through the array insertion sort imagine that you have st...
20,295
must make its way to the top of the array this would occur if the keys are initially arranged from highest to lowestin the reverse of sorted order in this casethe number of comparisons will be one the first time through the for looptwo the second timeand so on thusthe total number of comparisons will be th( = in contra...
20,296
chap internal sorting = figure an illustration of bubble sort each column shows the array after the iteration with the indicated value of in the outer for loop values above the line in each column have been sorted arrows indicate the swaps that take place during given iteration bubble sort our next sort is called bubbl...
20,297
determining bubble sort' number of comparisons is easy regardless of the arrangement of the values in the arraythe number of comparisons made by the inner for loop is always ileading to total cost of th( = bubble sort' running time is roughly the same in the bestaverageand worst cases the number of swaps required depen...
20,298
chap internal sorting = figure an example of selection sort each column shows the array after the iteration with the indicated value of in the outer for loop numbers above the line in each column have been sorted and are in their final positions key key key key key key key key ( (bfigure an example of swapping pointers...
20,299
insertion bubble selection comparisonsbest case average case worst case th(nth( th( th( th( th( th( th( th( swapsbest case average case worst case th( th( th( th( th(nth(nth(nfigure comparison of the asymptotic complexities for three simple sorting algorithms the cost of exchange sorting figure summarizes the cost of i...