id
int64
0
25.6k
text
stringlengths
0
4.59k
20,000
we can still use treesort howeverto output the sorted items into the original arraywe will need another procedure fillarray(tree tarray aint jto traverse the tree and fill the array that is easiest done by passing and returning an index that keeps track of the next array position to be filled this results in the comple...
20,001
with the highest priority appears in [nremoving this item would be very simplebut inserting new item would always involve finding the right position and shifting number of items to the right to make room for it for exampleinserting into the queue [ ] [ [ [ that kind of item insertion is effectively insertion sort and c...
20,002
time into the correct position in the sorted arrayheapsort(array aint nheapify( ,nforj -swap [ and [jbubbledown( , , - it is clear from the swap step that the order of identical items can easily be reversedso there is no way to render the heapsort algorithm stable the average and worst-case time complexities of the ent...
20,003
quicksort the general idea here is to repeatedly split (or partitionthe given array in such way that all the items in the first sub-array are smaller than all the items in the second sub-arrayand then concatenate all the sub-arrays to give the sorted full array how to partition the important question is how to perform ...
20,004
then the split will be as even as possible unfortunatelythere is no quick guaranteed way of finding the optimal pivot if the keys are integersone could take the average value of all the keysbut that requires visiting all the entries to sample their keyadding considerable overhead to the algorithmand if the keys are mor...
20,005
after the markers to give [cbasicadajava fortranocamlhaskellpascalsince we obviously cannot have the marker indices 'betweenarray entrieswe will assume the left marker is on the left of [leftmarkand the right marker is to the right of [rightmarkthe markers are therefore 'in the same placeonce rightmark becomes smaller ...
20,006
else [bcount++ [ifor bcount + [acount++ [ireturn right-bcount+ like the first partition procedurethis also achieves partitioning with the same items in the arraybut in different orderwith all items to the left of the returned pivot position smaller or equal to the pivot valueand all items to the right greater or equal ...
20,007
for defining the pivotsince the particular problem in question might well allow for more refined approach generallythe pivot will be better if more items are sampled before it is being chosen for exampleone could check several randomly chosen items and take the 'middleone of thosethe so called median note that in order...
20,008
we are using when arrays are usedit is actually necessary for the merge algorithm to create new array to hold the result of the operation at least temporarily in contrastwhen using linked listsit would be possible for merge to work by just changing the reference to the next node this does make for somewhat more confusi...
20,009
summary of comparison-based sorting algorithms the following table summarizes the key properties of all the comparison-based sorting algorithms we have consideredsorting algorithm bubble sort selection sort insertion sort treesort heapsort quicksort mergesort strategy employed exchange selection insertion insertion sel...
20,010
numbers from to how would you sort thosethe answer is surprisingly simple we know that we have entries in the array and we know exactly which items should go there and in which order this is very unusual situation as far as general sorting is concernedyet this kind of thing often comes up in every-day life for examplew...
20,011
binbucketradix sorts binbucketand radix sorts are all names for essentially the same non-comparison-based sorting algorithm that works well when the items are labelled by small sets of values for examplesuppose you are given number of datesby day and monthand need to sort them into order one way of doing this would be ...
20,012
phasecreate an ordered set of queues corresponding to the possible valuesthen add each item in the order they appear to the end of the relevant queueand finally concatenate the the queues in order repeat this process for each sorting criterion the crucial additional detail is that the queuing phases must be performed i...
20,013
hash tables storing data we have already seen number of different ways of storing items in computerarrays and variants thereof ( sorted and unsorted arraysheap trees)linked lists ( queuesstacks)and trees ( binary search treesheap treeswe have also seen that these approaches can perform quite differently when it comes t...
20,014
johnny james alex sherlock james english bond rider holmes moriarty spy spy spy detective villain the objects can be arbitrarily complicated howeverfor our purposesthe only relevant detail is that each object has unique keyand that their keys can be compared for equality the keys are used in order to identify objects i...
20,015
mechanisms for defining abstract data types but notice thatas opposed to specification in plain englishsuch as the abovea definition of an interface is only partial specification of an abstract data typebecause it does not explain what the methods are supposed to doit only explains how they are called implementations o...
20,016
this idea is not very practical if we are dealing with relatively small number of keys out of huge collection of possible keys for examplemany american companies use their employees -digit social security number as keyeven though they have nowhere near employees british national insurance numbers are even worsebecause ...
20,017
( ( ( ( )it may be surprising that ( and ( which means that as soon as there are more than people in groupit is more likely that two of them share birthday than not note that in the real worldthe distribution of birthdays over the year is not precisely uniformbut this only increases the probability that two people have...
20,018
now it is quite easy to go from any number (rather than stringto number from to for examplewe can take the remainder the number leaves when divided by this is the or java modulus operation so our hash function is ( ( )% % this modulo operationand modular arithmetic more generallyare widely used when constructing good h...
20,019
think of each column as bucket in which we throw all the elements which give particular result when the hash function is suppliedso the fifth column contains all the keys for which the hash function evaluates to then we could put hkg into the slot 'beneathphland gla in the one beneath oryand continue filling the table ...
20,020
(nmn (nmm - ) then linear search for an item in list of size takes on average ( + ** comparisons it is difficult to visualize what these formulae mean in practicebut if we assume the hash table is large but not overloadedi and are both large with mwe can perform taylor approximation for small loading factor / that show...
20,021
linear probing reduces the index by one to and finds an empty location in that positionso we put hkg there givinghkg phl gcm ory next we wish to insert glawith hash value but the location with that index is already filled by ory again linear probing reduces the index by oneand since that slot one to the left is freewe ...
20,022
on the other handwe are trying to insert keythen we can ignore any exclamation marks and fill the position once again this now does take care of all our problemsalthough if we do lot of deleting and insertingwe will end up with table which is bit of mess large number of exclamation marks means that we have to keep look...
20,023
divided by thus we would like to use as our secondary hash function ( ( / )% howeverthis has yet another problemit might give zero at some pointand we obviously cannot test 'every zeroth locationan easy solution is to simply make the secondary hash function one if the above would evaluate to zerothat is( / )% if ( / )%...
20,024
choosing good hash functions in principleany convenient function can be used as primary hash function howeverwhat is important when choosing good hash function is to make sure that it spreads the space of possible keys onto the set of hash table indices as evenly as possibleor more collisions than necessary will occur ...
20,025
maintainis dependent on the circumstances the following table shows comparison of the average time complexities for the different possible implementations of the table interfacesorted array balanced bst hash table search (log no(log no( insert (no(log no( delete (no(log no( traverse (no(no(nlog nhash tables are seen to...
20,026
graphs often it is useful to represent information in more general graphical form than considered so farsuch as the following representation of the distances between townsglasgow edinburgh newcastle manchester birmingham swansea london exeter with similar structures (maybe leaving out the distancesor replacing them by ...
20,027
would be the shortest set of pipes connecting all the locations there is also the famous travelling salesman problem which involves finding the shortest route through the structure that visits each city precisely once graph terminology the kind of structure in the above figure is known formally as graph graph consists ...
20,028
directed graphsthe notion of connectedness has two distinct versionswe say that digraph is weakly connected if for every two vertices and there is either path from to or path from to we say it is strongly connected if there are paths leading both ways soin weakly connected digraphthere may be two vertices and such that...
20,029
isthere is no edge from the vertex to the vertex ' 'on the other handreads as trueindicating that there is an edge it is often useful to use boolean values hererather than the numbers and because it allows us to carry out operations on the booleans in the second casewe have weighted graphand we have the real-valued wei...
20,030
treeswhich is essentially generalization of linked listscan be generalized for graphs in language such as javaa class graph might have the following as an internal classclass vertex string namevertex[neighboursdouble[weightswhen each vertex is createdan array neighbours big enough to accommodate (pointers toall its nei...
20,031
in two graphs and can then be defined as being homeomorphic if there is graph isomorphism from some subdivision of to some subdivision of an edge contraction removes an edge from graph and merges the two vertices previously connected by it this can lead to multiple edges between pair of verticesor self-loops connecting...
20,032
theorems about planarity the most well-known of these is kuratowski' theorem which states that " finite graph is planar if and only if it does not contain subgraph that is homeomorphic toor subdivision ofk or , anotherbased on the concept of minorsis wagner' theorem which states that " finite graph is planar if and onl...
20,033
added and processed note that with both breadth first and depth firstthe order of the vertices depends on the implementation there is no reason why ' neighbour should be visited before in the example so it is better to speak of result of depth first or breadth first traversalrather than of the result note also that the...
20,034
we currently have of the distance from to we initially have [ and set [zfor all vertices other than the start node then the algorithm repeatedly decreases the overestimates until it is no longer possible to decrease them further when this happensthe algorithm terminateswith each estimate fully constrained and said to b...
20,035
/all entries in the array 'tighthold the value true repeat as many times as there are vertices in the graph find vertex with tight[ufalse and minimal estimate [utight[utrue for each vertex adjacent to if [uweight[ ][zd[zd[zd[uweight[ ][ /lower overestimate exists /at this pointall entries of array 'dhold tight estimate...
20,036
of the three arrays at each intermediate stagegives the following outputin which"oois used to represent the infinity symbol ""computing shortest paths from | + | oo oo oo oo tight |no no no no no pred |none none none none none vertex has minimal estimateand so is tight neighbour has estimate decreased from oo to taking...
20,037
neighbour has estimate unchanged | + | tight |yes yes yes yes no pred |none vertex has minimal estimateand so is tight neighbour is already tight neighbour is already tight | + | tight |yes yes yes yes yes pred |none end of dijkstra' computation shortest path from to isa once it is clear what is happening at each stage...
20,038
/ start vertex ' /outputan array 'dof distances as explained above /we begin by buiding the distance overestimates [ /the shortest path from to itself has length zero for each vertex of the graph if is not the start vertex [zinfinity /this is certainly an overestimate /then we set up priority queue based on the overest...
20,039
this case the time complexity for both priority queue versions is (nlog )which is clear improvement over the previous ( algorithm shortest paths floyd' algorithm if we are not only interested in finding the shortest path from one specific vertex to all the othersbut the shortest paths between every pair of verticeswe c...
20,040
then multiple runs of dijkstra' algorithm can be made to perform with time complexity ( log )and be faster than floyd' algorithm simple example suppose we want to compute the lengths of the shortest paths between all vertices in the following undirected weighted graphwe start with distance matrix based on the connectio...
20,041
ea ' ' ' ' ' ' ' ' ' ' 'dd ' 'dc 'dd 'dd ' 'ee 'ec the algorithm finishes with the matrix of shortest distances and the matrix of associated predecessors so the shortest distance from to is and the predecessors of are ethen dthen cgiving the path note that updating distance does not necessarily mean updating the associ...
20,042
of graph is subgraph that is tree which connects all the vertices togetherso it 'spansthe original graph but using fewer edges hereminimal refers to the sum of all the weights of the edges contained in that treeso minimal spanning tree has total weight less than or equal to the total weight of every other spanning tree...
20,043
weights of those edgeswe could save timebecause we would then only have to check the weights mentioned in that array or list for the above graphstarting with { }the tree is built up as followsa it is slightly more challenging to produce convincing argument that this algorithm really works than it has been for the other...
20,044
edges in that are not in and we end up with the minimal spanning tree xn which completes the proof that is minimal spanning tree the time complexity of the standard prim' algorithm is ( because at each step we need to choose vertex to add to sand then update the closest arraynot dissimilar to the simplest form of dijks...
20,045
have the same (nlog ncomplexity as the optimal priority queue based versions of prim' algorithmbut will be faster than the standard ( prim' algorithm howeverif the graph is highly connectedi the number of edges is near the square of the number of verticesit will have complexity ( log nand be slower than the optimal ( v...
20,046
epilogue hopefully the reader will agree that these notes have achieved their objective of introducing the basic data structures used in computer scienceand showing how they can be used in the design of useful and efficient algorithms the basic data structures (arrayslistsstacksqueues and treeshave been employed throug...
20,047
some useful formulae the symbols abcr and represent real numbersm and are positive integersand indices and are non-negative integers binomial formulae ( ) ab ( ) ab ( )( ba ( ) ab powers and roots - /(ar ar as ar+ as bs (ab) (ar ) ars asr (as ) / ar /as ar- as /bs ( / ) and the following are special cases of the aboven...
20,048
loga (bcloga loga loga ( /cloga loga loga (br loga and the following are special cases of those ruleslog an log log ( /nlog for large we have the useful approximationlog nn log (na sums we often find it useful to abbreviate sum as followssn ai an = we can view this as an algorithm or programlet hold the sum at the enda...
20,049
vii heapsort binsort and radix sort an empirical comparison of sorting algorithms lower bounds for sorting further reading exercises projects file processing and external sorting primary versus secondary storage disk drives disk drive architecture disk access costs buffers and buffer pools the programmer' view of files...
20,050
contents further reading exercises projects indexing linear indexing isam tree-based indexing - trees -trees -trees -tree analysis further reading exercises projects iv advanced data structures graphs terminology and representations graph implementations graph traversals depth-first search breadth-first search topologi...
20,051
ix lists and arrays revisited multilists matrix representations memory management dynamic storage allocation failure policies and garbage collection further reading exercises projects advanced tree structures tries balanced trees the avl tree the splay tree spatial data structures the - tree the pr quadtree other point...
20,052
contents amortized analysis further reading exercises projects lower bounds introduction to lower bounds proofs lower bounds on searching lists searching in unsorted lists searching in sorted lists finding the maximum value adversarial lower bounds proofs state space lower bounds proofs finding the ith best element opt...
20,053
exercises projects xi limits to computation reductions hard problems the theory of -completeness -completeness proofs coping with -complete problems impossible problems uncountability the halting problem is unsolvable further reading exercises projects bibliography index
20,054
we study data structures so that we can learn to write more efficient programs but why must programs be efficient when new computers are faster every yearthe reason is that our ambitions grow with our capabilities instead of rendering efficiency needs obsoletethe modern revolution in computing power and storage capabil...
20,055
preface related to costs and benefits is the notion of tradeoffs for exampleit is quite common to reduce time requirements at the expense of an increase in space requirementsor vice versa programmers face tradeoff issues regularly in all phases of software design and implementationso the concept must become deeply ingr...
20,056
xv data structures will also benefit from having first completed good course in discrete mathematics nonetheless attempts to give reasonably complete survey of the prerequisite mathematical topics at the level necessary to understand their use in this book readers may wish to refer back to the appropriate sections as n...
20,057
preface make the examples as clear as possible while maintaining the advantages of java java is used here strictly as tool to illustrate data structures concepts in particulari make use of java' support for hiding implementation detailsincluding features such as classesprivate class membersand interfaces these features...
20,058
xvii my implementations are meant to provide concrete illustrations of data structure principlesas an aid to the textual exposition code examples should not be read or used in isolation from the associated text because the bulk of each example' documentation is contained in the textnot the code the code complements the...
20,059
preface one of the most important aspects of course in data structures is that it is where students really learn to program using pointers and dynamic memory allocationby implementing data structures such as linked lists and trees its also where students truly learn recursion in our curriculumthis is the first course w...
20,060
xix virginia tech helped make this whole thing possible through sabbatical research leave during fall enabling me to get the project off the ground my department heads during the time have written the various editions of this bookdennis kafura and jack carrollprovided unwavering moral support for this project mike keen...
20,061
preface others at prentice hall who helped me along the way include truly donovanlinda behrensand phyllis bregman am sure owe thanks to many others at prentice hall for their help in ways that am not even aware of wish to express my appreciation to hanan samet for teaching me about data structures learned much of the p...
20,062
preliminaries
20,063
data structures and algorithms how many cities with more than , people lie within miles of dallastexashow many people in my company make over $ , per yearcan we connect all of our telephone customers with less than , miles of cableto answer questions like theseit is not enough to have the necessary information we must ...
20,064
chap data structures and algorithms to design an algorithm that is easy to understandcodeand debug to design an algorithm that makes efficient use of the computer' resources ideallythe resulting program is true to both of these goals we might say that such program is "elegant while the algorithms and program code examp...
20,065
in the most general sensea data structure is any data representation and its associated operations even an integer or floating point number stored on the computer can be viewed as simple data structure more typicallya data structure is meant to be an organization or structuring for collection of data items sorted list ...
20,066
chap data structures and algorithms this three-step approach to selecting data structure operationalizes datacentered view of the design process the first concern is for the data and the operations to be performed on themthe next concern is the representation for those dataand the final concern is the implementation of...
20,067
bank uses in its interactions with its customersand ( the requirements for the database system that manages the accounts the typical customer opens and closes accounts far less often than he or she accesses the account customers are willing to wait many minutes while accounts are created or deleted but are typically no...
20,068
chap data structures and algorithms example company is developing database system containing information about cities and towns in the united states there are many thousands of cities and townsand the database program should allow users to find information about particular place by name (another example of an exact-mat...
20,069
data type is type together with collection of operations to manipulate the type for examplean integer variable is member of the integer data type addition is an example of an operation on the integer data type distinction should be made between the logical concept of data type and its physical implementation in compute...
20,070
chap data structures and algorithms fortunatelythe int implementation is not completely true to the abstract integeras there are limitations on the range of values an int variable can store if these limitations prove unacceptablethen some other representation for the adt "integermust be devisedand new implementation mu...
20,071
example when operating carthe primary activities are steeringacceleratingand braking on nearly all passenger carsyou steer by turning the steering wheelaccelerate by pushing the gas pedaland brake by pushing the brake pedal this design for cars can be viewed as an adt with operations "steer,"accelerate,and "brake two c...
20,072
chap data structures and algorithms example consider the design for relatively simple database system stored on disk typicallyrecords on disk in such program are accessed through buffer pool (see section rather than directly variable length records might use memory manager (see section to find an appropriate location w...
20,073
sec design patterns data type adttype operations data itemslogical form data structurestorage space data itemsphysical form subroutines figure the relationship between data itemsabstract data typesand data structures the adt defines the logical form of the data type the data structure implements the physical form of th...
20,074
chap data structures and algorithms layout for document the letter "cmight reasonably be represented by an object that describes that character' strokes and bounding box howeverwe don' want to create separate "cobject everywhere in the document that "cappears the solution is to allocate single copy of the shared repres...
20,075
composite there are two fundamental approaches to dealing with the relationship between collection of actions and hierarchy of object types first consider the typical procedural approach say we have base class for page layout entitieswith subclass hierarchy to define specific subtypes (pagecolumnsrowsfigurescharacterse...
20,076
chap data structures and algorithms any of the existing subclasses it merely requires that we define the behavior of each activity that can be performed on that subclass this second design approach of burying the functional activity in the subclasses is called the composite design pattern detailed example for using the...
20,077
problemsalgorithmsand programs programmers commonly deal with problemsalgorithmsand computer programs these are three distinct concepts problemsas your intuition would suggesta problem is task to be performed it is best thought of in terms of inputs and matching outputs problem definition should not include any constra...
20,078
chap data structures and algorithms algorithmsan algorithm is method or process followed to solve problem if the problem is viewed as functionthen an algorithm is an implementation for the function that transforms an input to the corresponding output problem can be solved by many different algorithms given algorithm so...
20,079
it must be composed of finite number of steps if the description for the algorithm were made up of an infinite number of stepswe could never hope to write it downnor implement it as computer program most languages for describing algorithms (including english and "pseudocode"provide some way to perform repeated actionsk...
20,080
chap data structures and algorithms to understand once you have mastered this book is algorithms by robert sedgewick [sed for an excellent and highly readable (but more advancedteaching introduction to algorithmstheir designand their analysissee introduction to algorithmsa creative approach by udi manber [man for an ad...
20,081
if you want to be successful java programmeryou need good reference manuals close at hand david flanagan' java in nutshell [fla provides good reference for those familiar with the basics of the language after gaining proficiency in the mechanics of program writingthe next step is to become proficient in program design ...
20,082
chap data structures and algorithms terms of its input and output then define two different physical representations for strings define an adt for list of integers firstdecide what functionality your adt should provide example should give you some ideas thenspecify your adt in java in the form of an abstract class decl...
20,083
imagine that you have been hired to design database service containing information about cities and towns in the united statesas described in example suggest two possible implementations for the database imagine that you are given an array of records that is sorted with respect to some key field contained in each recor...
20,084
chap data structures and algorithms imagine that you are programmer who must write function to sort an array of about integers from lowest value to highest value write down at least five approaches to sorting the array do not write algorithms in java or pseudocode just write sentence or two for each approach to describ...
20,085
mathematical preliminaries this presents mathematical notationbackgroundand techniques used throughout the book this material is provided primarily for review and reference you might wish to return to the relevant sections when you encounter unfamiliar notation or mathematical techniques in later section on estimating ...
20,086
chap mathematical preliminaries { { is positive integerxp / |pp qq pq pq - set composed of the members and set definition using set former examplethe set of all positive integers is member of set is not member of set the null or empty set cardinalitysize of set or number of members for set set is included in set qset i...
20,087
sec sets and relations examplebag [ is distinct from bag [ ]while set { is indistinguishable from set { howeverbag [ is indistinguishable from bag [ sequence is collection of elements with an orderand which may contain duplicate-valued elements sequence is also sometimes called tuple or vector in sequencethere is th el...
20,088
chap mathematical preliminaries example for the integersis an equivalence relation that partitions each element into distinct subset in other wordsfor any integer athree things are true if then aand if and cthen of coursefor distinct integers aband there are never cases where bb aor so the claims that is symmetric and ...
20,089
xry or yrx if every pair of distinct elements in partial order are comparablethen the order is called total order or linear order example for the integersthe relations and <both define partial orders operation is total order becausefor every pair of integers and such that yeither or likewise<is total order becausefor e...
20,090
while ngrows slower than nn (because any positive integer constant chap mathematical preliminaries pn/en )it grows faster than cn for permutationsa permutation of sequence is simply the members of arranged in some order for examplea permutation of the integers through would be those values arranged in some order if the...
20,091
positive integers for example mod mod mod and mod unfortunatelythere is more than one way to assign values to and rdepending on how integer division is interpreted the most common mathematical definition computes the mod function as mod mbn/mc in this case- mod howeverjava and +compilers typically use the underlying pr...
20,092
chap mathematical preliminaries in this booknearly all logarithms used have base of two this is because data structures and algorithms most often divide things in halfor store codes with binary bits whenever you see the notation log in this bookeither log is meant or else the term is being used asymptotically and the a...
20,093
sec summations and recurrences summations and recurrences most programs contain loop constructs when analyzing running time costs for programs with loopswe need to add up the costs for each time the loop is executed this is an example of summation summations are simply the sum of costs for some function applied to rang...
20,094
chap mathematical preliminaries ai = an+ for - ( as special cases to equation ni ( = and + ( = as corollary to equation log xn log + ( = finallyn = + ( the sum of reciprocals from to ncalled the harmonic series and written hn has value between loge and loge to be more preciseas growsthe summation grows closer to ( wher...
20,095
sec summations and recurrences from this definition we see that the first seven numbers of the fibonacci sequence are and notice that this definition contains two partsthe general definition for fib(nand the base cases for fib( and fib( likewisethe definition for factorial contains recursive part and base cases recurre...
20,096
chap mathematical preliminaries because we have merely guessed at pattern and not actually proved that this is the correct closed form solutionwe can use an induction proof to complete the process (see example example slightly more complicated recurrence is (nt( nt ( expanding this recurrence few stepswe get (nt( ( ( (...
20,097
factorial of trace of fact' execution for small value of is presented in section static long fact(int /compute nrecursively /fact( is the largest value that fits in long assert ( > &( < " out of range"if ( < return /base casereturn base solution return fact( - )/recursive call for the first two lines of the function co...
20,098
chap mathematical preliminaries ( (bfigure towers of hanoi example (athe initial conditions for problem with six rings (ba necessary intermediate step on the road to solution how can you solve this problemit is easy if you don' think too hard about the details insteadconsider that all rings are to be moved from pole to...
20,099
static void toh(int npole startpole goalpole tempif ( = return/base case toh( - starttempgoal)/recursive calln- rings move(startgoal)/move bottom disk to goal toh( - tempgoalstart)/recursive calln- rings those who are unfamiliar with recursion might find it hard to accept that it is used primarily as tool for simplifyi...