id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
21,100 | if we implement the priority queue using sorted listthen we improve the running time of phase to ( )for each operation removemin on now takes ( time unfortunatelyphase now becomes the bottleneck for the running timesincein the worst caseeach insert operation takes time proportional to the size of this sorting algorithm... |
21,101 | againby recalling proposition phase runs in ( timeand henceso does the entire insertion-sort algorithm alternativelywe could change our definition of insertion-sort so that we insert elements starting from the end of the priority-queue list in phase in which case performing insertion-sort on sequence that is already so... |
21,102 | data structure allows us to perform both insertions and removals in logarithmic timewhich is significant improvement over the list-based implementations discussed in section the fundamental way the heap achieves this improvement is to abandon the idea of storing entries in list and take the approach of storing entries ... |
21,103 | minimum keywhich will always be at the root of the heap for the sake of efficiencyas will become clear laterwe want the heap to have as small height as possible we enforce this requirement by insisting that the heap satisfy an additional structural propertyit must be complete before we define this structural propertywe... |
21,104 | hlogn justificationfrom the fact that is completewe know that the number of nodes of is at least - this lower bound is achieved when there is only one node on level in additionalso following from being completewe have that the number of nodes of is at most this upper bound is achieved when level has nodes since the num... |
21,105 | as an abstract data typea complete binary supports all the methods of binary tree adt (section )plus the following two methodsadd( )add to and return new external node storing element such that the resulting tree is complete binary tree with last node remove()remove the last node of and return its element using only th... |
21,106 | the array-list binary tree representation (section is especially suitable for complete binary tree we recall that in this implementationthe nodes of are stored in an array list such that node in is the element of with index equal to the level number (vof vdefined as followsif is the root of tthen ( if is the left child... |
21,107 | array list aid in the implementation of methods add and remove assuming that no array expansion is necessarymethods add and remove can be performed in ( timefor they simply involve adding or removing the last element of the array list moreoverthe array list associated with has elements (the element at index is place-ho... |
21,108 | fragment code fragment class arraylistcompletebinarytree implementing the complete binary tree adt (continues in code fragment |
21,109 | arraylistcompletebinarytree implementing the complete binary tree adt methods children and positions are omitted (continued from code fragment |
21,110 | we now discuss how to implement priority queue using heap our heap-based representation for priority queue consists of the following (see figure )heapa complete binary tree whose internal nodes store entries so that the heap-order property is satisfied we assume is implemented using an array listas described in section... |
21,111 | the heap of figure (ainitial heap(bafter performing operation add( and dswap to locally restore the partial order property( and fanother swap( and hfinal swap |
21,112 | conventionally called up-heap bubbling swap either resolves the violation of the heap-order property or propagates it one level up in the heap in the worst caseup-heap bubbling causes the new entry to move all the way up to the root of heap (see figure thusin the worst casethe number of swaps performed in the execution... |
21,113 | algorithm for performing method removemin using heap is illustrated in figure we know that an entry with the smallest key is stored at the root of (even if there is more than one entry with smallest keyhoweverunless is the only internal node of twe cannot simply delete node rbecause this action would disrupt the binary... |
21,114 | table shows the running time of the priority queue adt methods for the heap implementation of priority queueassuming that two keys can be compared in ( time and that the heap is implemented with either an array list or linked structure |
21,115 | performance of priority queue realized by means of heapwhich is in turn implemented with an array list or linked structure we denote with the number of entries in the priority queue at the time method is executed the space requirement is (nthe running time of operations insert and removemin is worst case for the array-... |
21,116 | priority queue adtindependent of whether the heap is implemented with linked structure or an array list the heap-based implementation achieves fast running times for both insertion and removalunlike the list-based priority queue implementations indeedan important consequence of the efficiency of the heapbased implement... |
21,117 | methods mininsert and removemin and some auxiliary methods of class heappriorityqueue (continues in code fragment |
21,118 | remaining auxiliary methods of class heappriorityqueue (continued from code fragment |
21,119 | |
21,120 | advantage that all the methods in the priority queue adt run in logarithmic time or better hencethis realization is suitable for applications where fast running times are sought for all the priority queue methods thereforelet us again consider the priorityqueuesort sorting scheme from section which uses priority queue ... |
21,121 | small amount of space in addition to the sequence itself instead of transferring elements out of the sequence and then back inwe simply rearrange them we il lustrate in-place heap-sort in figure in generalwe say that sorting algorithm is in-place if it uses only small amount of memory in addition to the sequence storin... |
21,122 | the analysis of the heap-sort algorithm shows that we can construct heap storing entries in (nlogntimeby means of successive insert operationsand then use that heap to extract the entries in order by nondecreasing key howeverif all the key-value pairs to be stored in the heap are given in advancethere is an al ternativ... |
21,123 | steps in the first step (see figure )we construct ( )/ elementary heaps storing one entry each in the second step (see figure - )we form ( )/ heapseach stor ing three entriesby joining pairs of elementary heaps and adding new entry the new entry is placed at the root and may have to be swapped with the entry stored at ... |
21,124 | we can also describe bottom-up heap construction as recursive algorithmas shown in code fragment which we call by passing list storing the keyvalue pairs for which we wish to build heap code fragment recursive bottom-up heap construction |
21,125 | keys into an initially empty heapas the following proposition shows proposition bottom-up construction of heap with entries takes (ntimeassuming two keys can be compared in ( time justificationwe analyze bottom-up heap construction using "visualap proachwhich is illustrated in figure let be the final heaplet be node of... |
21,126 | time of bottom-up heap con structionwhere the paths associated with the internal nodes have been highlighted with alternating colors for examplethe path associated with the root consists of the nodes storing keys and alsothe path associated with the right child of the root consists of the internal nodes storing keys an... |
21,127 | associated with this passenger operation removemin is not suitable for this purpose since the passenger leaving is unlikely to have first priority insteadwe would like to have new operation remove (ethat removes an arbitrary entry another standby passenger finds her gold frequent-flyer card and shows it to the agent th... |
21,128 | {( , )( , )insert( ,ce {( , ),( , ),( , )min( ( , ),( , ),( , )getkey( {( , ),( , ),( , )remove( ( , )( , )replacekey( , {( , ),( , )replace value( ,dc {( , ),( , )remove( {( , ) |
21,129 | location-aware entries in order to implement methods removereplacekeyand replacevalue of an adapt able priority queue pwe need mechanism for finding the position of an entry of namelygiven the entry of passed as an argument to one of the above methodswe need to find the position storing in the the data structure imple ... |
21,130 | data structures with location-aware entries is summarized in table table running times of the methods of an adaptable priority queue of size nrealized by means of an unsorted listsorted listand heaprespectively the space requirement is (nmethod unsorted list sorted list heap sizeisempty ( ( ( insert ( (no(lognmin (no( ... |
21,131 | ( ( (lognreplacekey ( (no(lognreplacevalue ( ( ( implementing an adaptable priority queue in code fragment and we show the java implementation of an adaptable priority queue based on sorted list this implementation is obtained by extending class sortedlistpriorityqueue shown in code fragment in particularcode fragment ... |
21,132 | an adaptable priority queue implemented with sorted list storing location-aware entries (continued from code fragment the |
21,133 | sortedlistpriorityqueue shown in code fragment |
21,134 | exercises for source code and help with exercisesplease visit java datastructures net reinforcement - suppose you label each node of binary tree with key equal to the preorder rank of under what circumstances is heapr- what is the output from the following sequence of priority queue adt methodsinsert( , )insert( , )ins... |
21,135 | sequence( , , , , , , , , , - illustrate the execution of the insertion-sort algorithm on the input se quence of the previous problem - give an example of worst-case sequence with elements for insertion sortand show that insertion-sort runs in ohm( time on such sequence - at which nodes of heap can an entry with the la... |
21,136 | about postorder traversal of hr- show that the sum which appears in the analysis of heap-sortis ohm(nlognr- bill claims that preorder traversal of heap will list its keys in nonde creasing order draw an example of heap that proves him wrong - hillary claims that postorder traversal of heap will list its keys in non inc... |
21,137 | turn the player with the most money must give half of his/her money to the player with the least amount of money what data structure(sshould be used to play this game efficientlywhycreativity - an online computer system for trading stock needs to process orders of the form "buy shares at $ eachor "sell shares at $ each... |
21,138 | space for instance variables in addition to an input array itself - assuming the input to the sorting problem is given in an array adescribe how to implement the insertion-sort algorithm using only the array andat mostsix additional (base-typevariables - describe how to implement the heap-sort algorithm usingat mostsix... |
21,139 | we can represent path from the root to given node of binary tree by means of binary stringwhere means "go to the left childand means "go to the right child for examplethe path from the root to the node storing ( ,win the heap of figure is represented by " design an (logn)-time algorithm for finding the last node of com... |
21,140 | suppose two binary treest and hold entries satisfying the heap-order property describe method for combining and into tree whose internal nodes hold the union of the entries in andt and also satisfy the heap-order property your algorithm should run in time ( where and are the respective heights of and - give an alternat... |
21,141 | give java implementation of priority queue based on an unsorted list - write an applet or stand-alone graphical program that animates both the insertion-sort and selection-sort algorithms your animation should visu alize the movement of elements to their correct locations - write an applet or stand-alone graphical prog... |
21,142 | one of the main applications of priority queues is in operating systems for scheduling jobs on cpu in this project you are to build program that schedules simulated cpu jobs your program should run in loopeach iteration of which corresponds to time slice for the cpu each job is assigned prioritywhich is an integer betw... |
21,143 | maps and dictionaries contents the map abstract data type simple list-based map implementation hash tables bucket arrays hash functions hash codes |
21,144 | compression functions collision-handling schemes java hash table implementation load factors and rehashing applicationcounting word frequencies the dictionary abstract data type list-based dictionaries and audit trails hash table dictionary implementation |
21,145 | ordered search tables and binary search skip lists search and update operations in skip list probabilistic analysis of skip lists extensions and applications of dictionaries supporting location-aware dictionary entries the ordered dictionary adt flight databases and maxima sets |
21,146 | java datastructures net the map abstract data type map allows us to store elements so they can be located quickly using keys the motivation for such searches is that each element typically stores additional useful information besides its search keybut the only way to get at that information is to use the search key spe... |
21,147 | user to an associated value object thusa map is most appropriate in situations where each key is to be viewed as kind of unique index address for its valuethat isan object that serves as kind of location for that value for exam pleif we wish to store student recordswe would probably want to use student id objects as ke... |
21,148 | its valueif has no such entrythen return null keys()return an iterable collection containing all the keys stored in (so keys(iterator(returns an iterator of keysvalues()return an iterable collection containing all the values as sociated with keys stored in (so values(iterator(re turns an iterator of valuesentries()retu... |
21,149 | {( , )( , )put( ,cnull {( , )( , )( , )put( ,dnull {( , )( , )( , )( , )put( ,ec {( , )( , )( , )( , )get( {( , )( , )( , )( , )get( null {( , )( , )( , )( , )get( {( , )( , )( , )( , )size( {( , )( , )( , )( , )remove( |
21,150 | remove( {( , )( , )get( null {( , )( , )isempty(false {( , )( , )maps in the java util package the java package java util includes an interface for the map adtwhich is called java util map this interface is defined so that an implementing class enforces unique keysand it includes all of the methods of the map adt given... |
21,151 | put( ,vput( ,vremove(kremove(kkeys(keyset(values(values(entries(entryset( simple list-based map implementation simple way of implementing map is to store its entries in list simplemented as doubly linked list performing the fundamental methodsget( )put(kv)and remove( )involves simple scans down looking for an entry wit... |
21,152 | hash tables the keys associated with values in map are typically thought of as "addressesfor those values examples of such applications include compiler' symbol table and registry of environment variables both of these structures consist of collection of symbolic names where each name serves as the "addressfor properti... |
21,153 | perform these operations in ( expected time in generala hash table consists of two major componentsa bucket array and hash function bucket arrays bucket array for hash table is an array of size nwhere each cell of is thought of as "bucket(that isa collection of key-value pairsand the integer defines the capacity of the... |
21,154 | different entries will be mapped to the same bucket in in this casewe say that collision has occurred clearlyif each bucket of can store only single entrythen we cannot associate more than one entry with single bucketwhich is problem in the case of collisions to be surethere are ways of dealing with collisionswhich we ... |
21,155 | the generic object class defined in java comes with default hashcode(method for mapping each object instance to an integer that is "representationof that ob ject specificallythe hashcode(method returns -bit integer of type int un less specifically overriddenthis method is inherited by every object used in java program ... |
21,156 | indeedthe approach of summing components can be extended to any object whose binary representation can be viewed as -tuple ( , , - of for examplegiven integersfor we can then form hash code for as any floating point numberwe can sum its mantissa and exponent as long integersand then apply hash code for long integers to... |
21,157 | or produced less than collisions in each caseit should come as no surprisethento learn that many java implementations choose the polynomial hash functionusing one of these constants for aas default hash code for strings for the sake of speedhoweversome java implementations only apply the polynomial hash function to fra... |
21,158 | cyclic shift of this hash code reverts to the one that simply sums all the characters collisions shift total max |
21,159 | |
21,160 | compression functions the hash code for key will typically not be suitable for immediate use with bucket arraybecause the range of possible hash codes for our keys will typically exceed the range of legal indices of our bucket array that isincorrectly using hash code as an index into our bucket array may result in an a... |
21,161 | several different 'sthen there will still be collisions the mad method more sophisticated compression functionwhich helps eliminate repeated pat terns in set of integer keys is the multiply add and divide (or "mad"method this method maps an integer to |ai bmod nwhere is prime numberand (called scaling factorand > (call... |
21,162 | the fundamental map operationsas shown in code fragment code fragment the fundamental methods of the map adtimplemented with hash table that uses separate chaining to resolve collisions among its entries for each fundamental map operationinvolving key kthe separate-chaining approach delegates the handling of this opera... |
21,163 | exercise ( - in figure we give an illustration of hash table with separate chaining assuming we use good hash function to index the entries of our map in bucket array of capacity nwe expect each bucket to be of size / this valuecalled the load factor of the hash table (and denoted with )should be bounded by small const... |
21,164 | are writing program for small handheld device)then we can use the alternative approach of always storing each entry directly in bucketat most one entry per bucket this approach saves space because no auxiliary structures are employedbut it requires bit more complexity to deal with collisions there are several vari ants... |
21,165 | until reach ing the desired entry or an empty bucket (or returning back to where we started fromadditionallyour algorithm for put( ,vshould remember an available cell encountered during the search for ksince this is valid place to put new entry ( ,vthuslinear probing saves spacebut it complicates removals even with the... |
21,166 | in code fragments we show classhashtablemapwhich implements the map adt using hash table with linear probing to resolve collisions these code fragments include the entire implementation of the map adtexcept for the methods values(and entries()which we leave as an exercise ( - the main design elements of the java class ... |
21,167 | class hashtablemap implementing the map adt using hash table with linear probing (continues in code fragment |
21,168 | class hashtablemap implementing the map adt using hash table with linear probing (continued from code fragment we have omitted the values(and entries(methods in the listing aboveas they are similar to keys( |
21,169 | in the hash table schemes described abovewe should desire that the load factorx /nbe kept below experiments and average-case analyses suggest that we |
21,170 | for separate chaining the built-in class java util hashmapwhich imple ments the map adtuses the threshold as default maximum load factor and rehashes any time the load factor exceeds this (or an optional user-set load factorthe choice of is fine for separate chaining (which is the likely implementation in java util has... |
21,171 | an ideal data structure to use herefor we can use words as keys and word counts as values we show such an application in code fragment code fragment program for counting word frequencies in documentprint ing the most frequent word the document is parsed using the scanner classfor which we change the delimiter for separ... |
21,172 | the dictionary abstract data type like mapa dictionary stores key-value pairs (kv)which we call entrieswhere is the key and is the value similarlya dictionary allows for keys and values to be of any object type butwhereas map insists that entries have unique keysa dictionary allows for multiple entries to have the same... |
21,173 | section in an unordered dictionaryhoweverno order relation is assumed on the keyshenceonly equality testing between keys is used as an adtan (unordereddictionary supports the following methodssize()return the number of entries in isempty()test whether is empty find( )if contains an entry with key equal to kthen return ... |
21,174 | insert( , ( , {( )insert( , ( , {( , )( , )insert( , ( , {( , )( , )( , )insert( , ( , {( , )( , )( , ),( , )insert( , ( , {( , )( , )( , )( , )( , )find( ( , {( , )( , )( , )( , )( , )find( null {( , )( , )( , )( , )( , )find( ( , {( , )( , )( , )( , )( , ) |
21,175 | {( , )( , ){( , )( , )( , )( , )( , )size( {( , )( , )( , )( , )( , )remove(find( )( , {( , )( , )( , )( , )find( null {( , )( , )( , )( ,elist-based dictionaries and audit trails simple way of realizing dictionary uses an unordered list to store the key-value entries such an implementation is often called log file or ... |
21,176 | we assume that the list used for list-based dictionary is implemented with doubly linked list we give descriptions of the main dictionary methods for listbased implementation in code fragment in this simple implementationwe don' assume that an entry stores reference to its location in code fragment some of the main met... |
21,177 | |
21,178 | ordered list beginning with the memory usagewe note that the space required for list-based dictionary with entries is ( )since the linked list data structure has memory usage proportional to its size in additionwith this implementation of the dictionary adtwe can realize operation insert(kveasily and efficientlyjust by... |
21,179 | kept below our hash function spreads entries fairly uniformlyand we use separate chaining to resolve collisionsthen we can achieve ( )-time performance for the findremoveand insert methods and ( )-time performance for the findall methodwhere is the number of entries returned in additionwe can simplify the algorithms fo... |
21,180 | if the keys in dictionary come from total orderwe can store ' entries in an array list by nondecreasing order of the keys (see figure we specify that is an array listrather than node listfor the ordering of the keys in the array list allows for faster searching than would be possible had beensayimplemented with linked ... |
21,181 | realization of dictionary by means of an ordered search table we show only the keys for this dictionaryso as to highlight their ordering the space requirement of an ordered search table is ( )which is similar to the list-based dictionary implementation (section )assuming we grow and shrink the array supporting the arra... |
21,182 | if getkey()then we have found the entry we were looking forand the search terminates successfully returning if getkey()then we recur on the first half of the array listthat ison the range of indices from low to mid if getkey()we recur on the range of indices from mid to high this search method is called binary searchan... |
21,183 | ber of primitive operations are executed at each recursive call of method binary search hencethe running time is proportional to the number of recursive calls performed crucial fact is that with each recursive call the number of candidate entries still to be searched in the array list is given by the value high low mor... |
21,184 | thuswe have mlogn which implies that binary search runs in (logntime there is simple variation of binary search that performs findall(kin time (logn )where is the number of entries in the iterator returned the details are left as an exercise ( - thuswe can use an ordered search table to perform fast dictionary searches... |
21,185 | list hash table search table sizeisempty ( ( ( entries (no(no(nfind (no( exp (nworst-case (lognfindall (no( sexp (nworst-case (logn sinsert ( ( (nremove |
21,186 | ( exp (nworst-case ( skip lists an interesting data structure for efficiently realizing the dictionary adt is the skip list this data structure makes random choices in arranging the entries in such way that search and update times are (lognon averagewhere is the number of entries in the dictionary interestinglythe noti... |
21,187 | list with list at the bottom and lists , above it alsowe refer to as the height of skip list figure example of skip list storing entries for simplicitywe show only the keys of the entries intuitivelythe lists are set up so that + contains more or less every other entry in as we shall see in the details of the insertion... |
21,188 | are also doubly linked lists search and update operations in skip list the skip list structure allows for simple dictionary search and update algorithms in factall of the skip list search and update algorithms are based on an elegant skipsearch method that takes key and finds the position of the entry in list such that... |
21,189 | skipsearchin code fragment given this methodit is now easy to implement the operation find(kwe simply perform skipsearch(kand test whether or not key(pk if these two keys are equalwe return potherwisewe return null code fragment search in skip list variable holds the start position of as it turns outthe expected runnin... |
21,190 | level as pand above position qreturning the position of the new entry (and setting internal references so that nextprevaboveand below methods will work correctly for pqand rthe expected running time of the insertion algorithm on skip list with entries is (logn)which we show in section code fragment insertion in skip li... |
21,191 | positions preceding them are flagged removal in skip list like the search and insertion algorithmsthe removal algorithm for skip list is quite simple in factit is even easier than the insertion algorithm that isto perform remove(koperationwe begin by executing method skipsearch(kif the position stores an entry with key... |
21,192 | highlighted in blue the positions removed are drawn with dashed lines maintaining the top-most level skip-list must maintain reference to the start position (the top-mostleft position in sas an instance variableand must have policy for any insertion that wishes to continue inserting new entry past the top level of ther... |
21,193 | howeversince the probability of having fair coin repeatedly come up heads forever is moreoverwe cannot infinitely add positions to list without eventually running out of memory in any caseif we terminate position insertion at the highest level hthen the worst-case running time for performing the findinsertand remove op... |
21,194 | nextconsider the running time of search in skip list sand recall that such search involves two nested while loops the inner loop performs scan forward on level of as long as the next key is no greater than the search key kand the outer loop drops down to the next level and repeats the scan forward iteration since the h... |
21,195 | performed with nand the size of the collection returned by operation findall with the expected space requirement is (noperation time sizeisempty ( entries (nfindinsertremove (logn(expectedfindall (logn (expected extensions and applications of dictionaries in this sectionwe explore several extensions and applications of... |
21,196 | structures presented in this unordered list in an unordered listlimplementing dictionarywe can maintain the location variable of each entry to point to ' position in the underlying linked list for this choice allows us to perform remove(eas remove( location())which would run in ( time hash table with separate chaining ... |
21,197 | (logn(expectedthe ordered dictionary adt in an ordered dictionarywe want to perform the usual dictionary operationsbut also maintain an order relation for the keys in our dictionary we can use comparator to provide the order relation among keysas we did for the ordered search table and skip list dictionary implementati... |
21,198 | methods of these iterators would each run in constant time using this approach the java util sorted map interface java provides an ordered version of the java util map interface in its interface called java util sortedmap this interface extends the java util map interface with methods that take order into account like ... |
21,199 | last(getvalue(get(lastkey()successors(ktailmap(kentryset(iterator(predecessors(kheadmap(kentryset(iterator(flight databases and maxima sets as we have mentioned in the preceding sectionsunordered and ordered dictionaries have many applications in this sectionwe explore some specific applications of ordered dictionaries... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.