id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
25,200 | this timehowevera has no unvisited neighborsso we pop it off the stack but now there' nothing left to popwhich brings up rule remember rule if you can' follow rule or rule you're finished table shows how the stack looks in the various stages of this processas applied to figure table stack contents during depth-first search event stack visit visit ab visit abf visit abfh pop abf pop ab pop visit ac pop visit ad visit adg visit adgi pop adg pop ad pop visit ae pop |
25,201 | done the contents of the stack is the route you took from the starting vertex to get where you are as you move away from the starting vertexyou push vertices as you go as you move back toward the starting vertexyou pop them the order in which you visit the vertices is abfhcdgie you might say that the depth-first search algorithm likes to get as far away from the starting point as quickly as possibleand returns only when it reaches dead end if you use the term depth to mean the distance from starting pointyou can see where the name depth-first search comes from an analogy an analogy you might think about in relation to depth-first search is maze the maze-perhaps one of the people-size ones made of hedgespopular in england--consists of narrow passages (think of edgesand intersections where passages meet (verticessuppose that someone is lost in the maze she knows there' an exit and plans to traverse the maze systematically to find it fortunatelyshe has ball of string and marker pen she starts at some intersection and goes down randomly chosen passageunreeling the string at the next intersectionshe goes down another randomly chosen passageand so onuntil finally she reaches dead end at the dead end she retraces her pathreeling in the stringuntil she reaches the previous intersection here she marks the path she' been down so she won' take it againand tries another path when she' marked all the paths leading from that intersectionshe returns to the previous intersection and repeats the process the string represents the stackit "remembersthe path taken to reach certain point the graphn workshop applet and dfs you can try out the depth-first search with the dfs button in the graphn workshop applet (the is for not directednot weighted start the applet at the beginningthere are no vertices or edgesjust an empty rectangle you create vertices by double-clicking the desired location the first vertex is automatically labeled athe second one is band so on they're colored randomly to make an edgedrag from one vertex to another figure shows the graph of figure as it looks when created using the applet |
25,202 | there' no way to delete individual edges or verticesso if you make mistakeyou'll need to start over by clicking the new buttonwhich erases all existing vertices and edges (it warns you before it does this clicking the view button switches you to the adjacency matrix for the graph you've madeas shown in figure clicking view again switches you back to the graph figure adjacency matrix view in graphnsearches to run the depth-first search algorithmclick the dfs button repeatedly you'll be prompted to click (not double-clickthe starting vertex at the beginning of the process you can re-create the graph of figure or you can create simpler or more complex ones of your own after you play with it whileyou can predict what the algorithm will do next (unless the graph is too weirdif you use the algorithm on an unconnected graphit will find only those vertices that are connected to the starting vertex java code key to the dfs algorithm is being able to find the vertices that are unvisited and adjacent to specified vertex how do you do thisthe adjacency matrix is the key by going to the row for the specified vertex and stepping across the columnsyou can pick out the columns with the column number is the number of an adjacent vertex you can then check whether this vertex is unvisited if soyou've found what you want--the next vertex to visit if no vertices on the row are simultaneously (adjacentand also unvisitedthen there are no unvisited vertices adjacent to the specified vertex we put the code for this process in the getadjunvisitedvertex(method/returns an unvisited vertex adjacent to public int getadjunvisitedvertex(int vfor(int = <nvertsj++if(adjmat[ ][ ]== &vertexlist[jwasvisited==falsereturn /return first such vertex return - /no such vertices /end getadjunvisitedvert( |
25,203 | depth-first search you can see how this code embodies the three rules listed earlier it loops until the stack is empty within the loopit does four things it examines the vertex at the top of the stackusing peek( it tries to find an unvisited neighbor of this vertex if it doesn' find oneit pops the stack if it finds such vertexit visits it and pushes it onto the stack here' the code for the dfs(methodpublic void dfs(/depth-first search /begin at vertex vertexlist[ wasvisited true/mark it displayvertex( )/display it thestack push( )/push it while!thestack isempty(/until stack empty/get an unvisited vertex adjacent to stack top int getadjunvisitedvertexthestack peek()if( =- /if no such vertexthestack pop()/pop new one else /if it existsvertexlist[vwasvisited true/mark it displayvertex( )/display it thestack push( )/push it /end while /stack is emptyso we're done for(int = <nvertsj++/reset flags vertexlist[jwasvisited false/end dfs at the end of dfs()we reset all the wasvisited flags so we'll be ready to run dfs(again later the stack should already be emptyso it doesn' need to be reset now we have all the pieces of the graph class we need here' some code that creates graph objectadds some vertices and edges to itand then performs depth-first searchgraph thegraph new graph()thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ (start for dfs |
25,204 | thegraph addedge( )thegraph addedge( )thegraph addedge( )/ab /bc /ad /de system out print("visits")thegraph dfs()/depth-first search system out println()figure shows the graph created by this code here' the outputvisitsabcde figure graph used by dfs java and bfs javasearches you can modify this code to create the graph of your choiceand then run it to see it carry out the depth-first search the dfs java program listing shows the dfs java programwhich includes the dfs(method it includes version of the stackx class from "stacks and queues listing the dfs java program /dfs java /demonstrates depth-first search /to run this programc>java dfsapp import java awt *///////////////////////////////////////////////////////////////class stackx private final int size private int[stprivate int toppublic stackx(/constructor st new int[size]/make array top - public void push(int /put item on stack st[++topj |
25,205 | /take item off stack return st[top--]public int peek(/peek at top of stack return st[top]public boolean isempty(/true if nothing on stack return (top =- )/end class stackx ///////////////////////////////////////////////////////////////class vertex public char label/label ( ' 'public boolean wasvisited/public vertex(char lablabel labwasvisited false/constructor //end class vertex ///////////////////////////////////////////////////////////////class graph private final int max_verts private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices private stackx thestack/public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix to adjmat[ ][ thestack new stackx()/end constructor /public void addvertex(char labvertexlist[nverts++new vertex(lab) |
25,206 | /public void addedge(int startint endadjmat[start][end adjmat[end][start /public void displayvertex(int vsystem out print(vertexlist[vlabel)/public void dfs(/depth-first search /begin at vertex vertexlist[ wasvisited true/mark it displayvertex( )/display it thestack push( )/push it while!thestack isempty(/until stack empty/get an unvisited vertex adjacent to stack top int getadjunvisitedvertexthestack peek()if( =- /if no such vertexthestack pop()else /if it existsvertexlist[vwasvisited true/mark it displayvertex( )/display it thestack push( )/push it /end while /stack is emptyso we're done for(int = <nvertsj++/reset flags vertexlist[jwasvisited false/end dfs //returns an unvisited vertex adj to public int getadjunvisitedvertex(int vfor(int = <nvertsj++if(adjmat[ ][ ]== &vertexlist[jwasvisited==falsereturn jreturn - /end getadjunvisitedvert(/ |
25,207 | /end class graph ///////////////////////////////////////////////////////////////class dfsapp public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ (start for dfsthegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ab /bc /ad /de system out print("visits")thegraph dfs()/depth-first search system out println()/end main(/end class dfsapp ///////////////////////////////////////////////////////////////breadth-first search as we saw in the depth-first searchthe algorithm acts as though it wants to get as far away from the starting point as quickly as possible in the breadth-first searchon the other handthe algorithm likes to stay as close as possible to the starting point it visits all the vertices adjacent to the starting vertexand only then goes further afield this kind of search is implemented using queue instead of stack an example figure shows the same graph as figure but here the breadth-first search is used againthe numbers indicate the order in which the vertices are visited figure breadth-first search is the starting vertexso you visit it and make it the current vertex then you follow these rules |
25,208 | rule visit the next unvisited vertex (if there is onethat' adjacent to the current vertexmark itand insert it into the queue remember rule if you can' carry out rule because there are no more unvisited verticesremove vertex from the queue (if possibleand make it the current vertex remember rule if you can' carry out rule because the queue is emptyyou're finished thus you first visit all the vertices adjacent to ainserting each one into the queue as you visit it now you've visited abcdand at this point the queue (from front to rearcontains bcde there are no more unvisited vertices adjacent to aso you remove from the queue and look for vertices adjacent to bso you remove from the queue it has no adjacent unvisited adjacent verticesso you remove and visit has no more adjacent unvisited verticesso you remove now the queue is fg you remove and visit hand then you remove and visit now the queue is hibut when you've removed each of these and found no adjacent unvisited verticesthe queue is emptyso you're finished table shows this sequence table queue contents during breadth-first search event queue (front to rearvisit visit visit bc visit bcd visit bcde remove cde visit cdef remove def remove ef visit efg |
25,209 | fg remove visit gh remove visit hi remove remove done at each momentthe queue contains the vertices that have been visited but whose neighbors have not yet been fully explored (contrast this with the depth-first searchwhere the contents of the stack is the route you took from the starting point to the current vertex the nodes are visited in the order abcdefghi the graphn workshop applet and bfs use the graphn workshop applet to try out breadth-first search using the bfs button againyou can experiment with the graph of figure or you can make up your own notice the similarities and the differences of the breadth-first search compared with the depth-first search you can think of the breadth-first search as proceeding like ripples widening when you drop stone in water--orfor those of you who enjoy epidemiologyas the influenza virus carried by air travelers from city to city firstall the vertices one edge (plane flightaway from the starting point are visitedthen all the vertices two edges away are visitedand so on java code the bfs(method of the graph class is similar to the dfs(methodexcept that it uses queue instead of stack and features nested loops instead of single loop the outer loop waits for the queue to be emptywhereas the inner one looks in turn at each unvisited neighbor of the current vertex here' the codepublic void bfs(/breadth-first search /begin at vertex vertexlist[ wasvisited true/mark it displayvertex( )/display it thequeue insert( )/insert at tail int while!thequeue isempty(/until queue emptyint thequeue remove()/remove vertex at head /until it has no unvisited neighbors |
25,210 | /get onevertexlist[ wasvisited true/mark it displayvertex( )/display it thequeue insert( )/insert it /end while(unvisited neighbors/end while(queue not empty/queue is emptyso we're done for(int = <nvertsj++vertexlist[jwasvisited false/reset flags /end bfs(given the same graph as in dfs java (shown earlier in figure )the output from bfs java is now visitsabdce the bfs java program the bfs java programshown in listing is similar to dfs java except for the inclusion of queue class (modified from the version in "linked lists"instead of stackx classand bfs(method instead of dfs(method listing the bfs java program /bfs java /demonstrates breadth-first search /to run this programc>java bfsapp import java awt *///////////////////////////////////////////////////////////////class queue private final int size private int[quearrayprivate int frontprivate int rearpublic queue(/constructor quearray new int[size]front rear - public void insert(int /put item at rear of queue if(rear =size- rear - quearray[++rearjpublic int remove(/take item from front of queue |
25,211 | if(front =sizefront return temppublic boolean isempty(/true if queue is empty return rear+ ==front |(front+size- ==rear)/end class queue ///////////////////////////////////////////////////////////////class vertex public char label/label ( ' 'public boolean wasvisited/public vertex(char lab/constructor label labwasvisited false//end class vertex ///////////////////////////////////////////////////////////////class graph private final int max_verts private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices private queue thequeue/public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix to adjmat[ ][ thequeue new queue()/end constructor / |
25,212 | public void addvertex(char labvertexlist[nverts++new vertex(lab)/public void addedge(int startint endadjmat[start][end adjmat[end][start /public void displayvertex(int vsystem out print(vertexlist[vlabel)/public void bfs(/breadth-first search /begin at vertex vertexlist[ wasvisited true/mark it displayvertex( )/display it thequeue insert( )/insert at tail int while!thequeue isempty(/until queue emptyint thequeue remove()/remove vertex at head /until it has no unvisited neighbors while( =getadjunvisitedvertex( )!- /get onevertexlist[ wasvisited true/mark it displayvertex( )/display it thequeue insert( )/insert it /end while /end while(queue not empty/queue is emptyso we're done for(int = <nvertsj++vertexlist[jwasvisited false/end bfs(/reset flags //returns an unvisited vertex adj to public int getadjunvisitedvertex(int vfor(int = <nvertsj++if(adjmat[ ][ ]== &vertexlist[jwasvisited==false |
25,213 | return - /end getadjunvisitedvert(//end class graph ///////////////////////////////////////////////////////////////class bfsapp public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ (start for dfsthegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ab /bc /ad /de system out print("visits")thegraph bfs()/breadth-first search system out println()/end main(/end class bfsapp ///////////////////////////////////////////////////////////////minimum spanning trees suppose that you've designed printed circuit board like the one shown in figure and you want to be sure you've used the minimum number of traces that isyou don' want any extra connections between pinssuch extra connections would take up extra room and make other circuits more difficult to lay out it would be nice to have an algorithm thatfor any connected set of pins and traces (vertices and edgesin graph terminology)would remove any extra traces the result would be graph with the minimum number of edges necessary to connect the vertices for examplefigure - shows five vertices with an excessive number of edgeswhile figure - shows the same vertices with the minimum number of edges necessary to connect them this constitutes minimum spanning tree figure minimum spanning tree |
25,214 | - shows edges abbccdand debut edges acceedand db would do just as well the arithmetically inclined will note that the number of edges in minimum spanning tree is always one less than the number of vertices ve= - remember that we're not worried here about the length of the edges we're not trying to find minimum physical lengthjust the minimum number of edges (this will change when we talk about weighted graphs in the next the algorithm for creating the minimum spanning tree is almost identical to that used for searching it can be based on either the depth-first search or the breadth-first search in our example we'll use the depth-first-search it turns out that by executing the depth-first search and recording the edges you've traveled to make the searchyou automatically create minimum spanning tree the only difference between the minimum spanning tree method mst()which we'll see in momentand the depth-first search method dfs()which we saw earlieris that mst(must somehow record the edges traveled graphn workshop applet repeatedly clicking the tree button in the graphn workshop algorithm will create minimum spanning tree for any graph you create try it out with various graphs you'll see that the algorithm follows the same steps as when using the dfs button to do search when using treehoweverthe appropriate edge is darkened when the algorithm assigns it to the minimum spanning tree when it' finishedthe applet removes all the non-darkened linesleaving only the minimum spanning tree final button press restores the original graphin case you want to use it again java code for the minimum spanning tree here' the code for the mst(methodwhile!thestack isempty(/until stack empty /get stack top int currentvertex thestack peek()/get next unvisited neighbor int getadjunvisitedvertex(currentvertex)if( =- /if no more neighbors thestack pop()/pop it away else /got neighbor vertexlist[vwasvisited true/mark it thestack push( )/push it /display edge displayvertex(currentvertex)/from currentv displayvertex( )/to system out print(")/end while(stack not empty/stack is emptyso we're done |
25,215 | /reset flags vertexlist[jwasvisited false/end mst(as you can seethis code is very similar to dfs(in the else statementhoweverthe current vertex and its next unvisited neighbor are displayed these two vertices define the edge that the algorithm is currently traveling to get to new vertexand it' these edges that make up the minimum spanning tree in the main(part of the mst java programwe create graph by using these statementsgraph thegraph new graph()thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )(start for mst/ab /ac /ad /ae /bc /bd /be /cd /ce /de the graph that results is the one shown in figure - when the mst(method has done its workonly four edges are leftas shown in figure - here' the output from the mst java programminimum spanning treeab bc cd de as we notedthis is only one of many possible minimum scanning trees that can be created from this graph using different starting vertexfor examplewould result in different tree so would small variations in the codesuch as starting at the end of the vertexlist[instead of the beginning in the getadjunvisitedvertex(method the mst java program listing shows the mst java program it' similar to dfs javaexcept for the mst(method and the graph created in main(listing the mst java program /mst java /demonstrates minimum spanning tree /to run this programc>java mstapp |
25,216 | ///////////////////////////////////////////////////////////////class stackx private final int size private int[stprivate int toppublic stackx(/constructor st new int[size]/make array top - public void push(int /put item on stack st[++topjpublic int pop(/take item off stack return st[top--]public int peek(/peek at top of stack return st[top]public boolean isempty(/true if nothing on stack return (top =- )///////////////////////////////////////////////////////////////class vertex public char label/label ( ' 'public boolean wasvisited/public vertex(char lab/constructor label labwasvisited false//end class vertex ///////////////////////////////////////////////////////////////class graph private final int max_verts private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix /current number of vertices private stackx thestack |
25,217 | /constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix to adjmat[ ][ thestack new stackx()/end constructor /public void addvertex(char labvertexlist[nverts++new vertex(lab)/public void addedge(int startint endadjmat[start][end adjmat[end][start /public void displayvertex(int vsystem out print(vertexlist[vlabel)/public void mst(/minimum spanning tree (depth first/start at vertexlist[ wasvisited true/mark it thestack push( )/push it while!thestack isempty(/until stack empty /get stack top int currentvertex thestack peek()/get next unvisited neighbor int getadjunvisitedvertex(currentvertex)if( =- /if no more neighbors thestack pop()/pop it away else /got neighbor |
25,218 | vertexlist[vwasvisited true/mark it thestack push( )/push it /display edge displayvertex(currentvertex)/from currentv displayvertex( )/to system out print(")/end while(stack not empty/stack is emptyso we're done for(int = <nvertsj++/reset flags vertexlist[jwasvisited false/end tree //returns an unvisited vertex adj to public int getadjunvisitedvertex(int vfor(int = <nvertsj++if(adjmat[ ][ ]== &vertexlist[jwasvisited==falsereturn jreturn - /end getadjunvisitedvert(//end class graph ///////////////////////////////////////////////////////////////class mstapp public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ (start for mstthegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ab /ac /ad /ae /bc /bd /be /cd /ce /de |
25,219 | system out print("minimum spanning tree")thegraph mst()/minimum spanning tree system out println()/end main(/end class mstapp ///////////////////////////////////////////////////////////////topological sorting with directed graphs topological sorting is another operation that can be modeled with graphs it' useful in situations in which items or events must be arranged in specific order let' look at an example an examplecourse prerequisites in high school and collegestudents find (sometimes to their dismaythat they can' take just any course they want some courses have prerequisites--other courses that must be taken first indeedtaking certain courses may be prerequisite to obtaining degree in certain field figure shows somewhat fanciful arrangement of courses necessary for graduating with degree in mathematics figure course prerequisites to obtain your degreeyou must complete the senior seminar and (because of pressure from the english departmentcomparative literature but you can' take senior seminar without having already taken advanced algebra and analytic geometryand you can' take comparative literature without taking english composition alsoyou need geometry for analytic geometryand algebra for both advanced algebra and analytic geometry directed graphs as the figure showsa graph can represent this sort of arrangement howeverthe graph needs feature we haven' seen beforethe edges need to have direction figure small directed graph when this is the casethe graph is called directed graph in directed graph you can only proceed one way along an edge the arrows in figure show the direction of |
25,220 | in programthe difference between non-directed graph and directed graph is that an edge in directed graph has only one entry in the adjacency matrix figure shows small directed graphtable shows its adjacency matrix table adjacency matrix for small directed graph each edge is represented by single the row labels show where the edge startsand the column labels show where it ends thusthe edge from to is represented by single at row column if the directed edge were reversed so that it went from to athere would be at row column instead for non-directed graphas we noted earlierhalf of the adjacency matrix mirrors the other halfso half the cells are redundant howeverfor weighted graphevery cell in the adjacency matrix conveys unique information for directed graphthe method that adds an edge thus needs only single statementpublic void addedge(int startint endadjmat[start][end /directed graph instead of the two statements required in non-directed graph if you use the adjacency-list approach to represent your graphthen has in its list but--unlike non-directed graph-- does not have in its list topological sorting imagine that you make list of all the courses necessary for your degreeusing figure as your input data you then arrange the courses in the order you need to take them obtaining your degree is the last item on the listwhich might look like thisbaedgcfh arranged this waythe graph is said to be topologically sorted any course you must take before some other course occurs before it in the list |
25,221 | the english courses and firstfor examplecfbaedgh this also satisfies all the prerequisites there are many other possible orderings as well when you use an algorithm to generate topological sortthe approach you take and the details of the code determine which of various valid sortings are generated topological sorting can model other situations besides course prerequisites job scheduling is an important example if you're building caryou want to arrange things so that brakes are installed before the wheels and the engine is assembled before it' bolted onto the chassis car manufacturers use graphs to model the thousands of operations in the manufacturing processto ensure that everything is done in the proper order modeling job schedules with graphs is called critical path analysis although we don' show it herea weighted graph (discussed in the next can be usedwhich allows the graph to include the time necessary to complete different tasks in project the graph can then tell you such things as the minimum time necessary to complete the project the graphd workshop applet the graphd workshop applet models directed graphs this applet operates in much the same way as graphn but provides dot near one end of each edge to show which direction the edge is pointing be carefulthe direction you drag the mouse to create the edge determines the direction of the edge figure shows the graphd workshop applet used to model the course-prerequisite situation of figure the idea behind the topological sorting algorithm is unusual but simple two steps are necessaryfigure the graphd workshop applet remember step find vertex that has no successors the successors to vertex are those vertices that are directly "downstreamfrom it--that isconnected to it by an edge that points in their direction if there is an edge pointing from to bthen is successor to in figure the only vertex with no successors is remember |
25,222 | steps and are repeated until all the vertices are gone at this pointthe list shows the vertices arranged in topological order you can see the process at work by using the graphd applet construct the graph of figure (or any other graphif you preferby double-clicking to make vertices and dragging to make edges then repeatedly click the topo button as each vertex is removedits label is placed at the beginning of the list below the graph deleting vertex may seem like drastic stepbut it' the heart of the algorithm the algorithm can' figure out the second vertex to remove until the first vertex is gone if you need toyou can save the graph' data (the vertex list and the adjacency matrixelsewhere and restore it when the sort is completedas we do in the graphd applet the algorithm works because if vertex has no successorsit must be the last one in the topological ordering as soon as it' removedone of the remaining vertices must have no successorsso it will be the next-to-last one in the orderingand so on the topological sorting algorithm works on unconnected graphs as well as connected graphs this models the situation in which you have two unrelated goalssuch as getting degree in mathematics and at the same time obtaining certificate in first aid cycles and trees one kind of graph the topological-sort algorithm cannot handle is graph with cycles what' cycleit' path that ends up where it started in figure the path - -db forms cycle (notice that - - - is not cycle because you can' go from to figure graph with cycle cycle models the catch- situation (which some students claim to have actually encountered at certain institutions)where course is prerequisite for course cc is prerequisite for dand is prerequisite for graph with no cycles is called tree the binary and multiway trees we saw earlier in this book are trees in this sense howeverthe trees that arise in graphs are more general than binary and multiway treeswhich have fixed maximum number of child nodes in grapha vertex in tree can be connected to any number of other verticesprovided that no cycles are created topological sort is carried out on directed graph with no cycles such graph is called directedacyclic graphoften abbreviated dag java code here' the java code for the topo(methodwhich carries out the topological sortpublic void topo(/toplogical sort |
25,223 | /remember how many verts while(nverts /while vertices remain/get vertex with no successorsor - int currentvertex nosuccessors()if(currentvertex =- /must be cycle system out println("errorgraph has cycles")return/insert vertex label in sorted array (start at endsortedarray[nverts- vertexlist[currentvertexlabeldeletevertex(currentvertex)/end while /delete vertex /vertices all gonedisplay sortedarray system out print("topologically sorted order")for(int = <orig_nvertsj++system out printsortedarray[ )system out println("")/end topo the work is done in the while loopwhich continues until the number of vertices is reduced to here are the steps involved call nosuccessors(to find any vertex with no successors if such vertex is foundput the vertex label at the end of sortedarray[and delete the vertex from the graph if an appropriate vertex isn' foundthe graph must have cycle the last vertex to be removed appears first on the listso the vertex label is placed in sortedarray starting at the end and working toward the beginningas nverts (the number of vertices in the graphgets smaller if vertices remain in the graph but all of them have successorsthe graph must have cycleand the algorithm displays message and quits normallyhoweverthe while loop exitsand the list from sortedarray is displayedwith the vertices in topologically sorted order the nosuccessors(method uses the adjacency matrix to find vertex with no successors in the outer for loopit goes down the rowslooking at each vertex for each vertexit scans across the columns in the inner for looplooking for if it finds oneit knows that that vertex has successorbecause there' an edge from that vertex to another one when it finds it bails out of the inner loop so that the next vertex can be investigated only if an entire row is found with no do we know we have vertex with no successorsin this caseits row number is returned if no such vertex is found- is returned here' the nosuccessors(method |
25,224 | /(or - if no such vertsboolean isedge/edge from row to column in adjmat for(int row= row<nvertsrow++/for each vertexisedge false/check edges for(int col= col<nvertscol++ifadjmat[row][col /if edge to /anotherisedge truebreak/this vertex /has successor /try another if!isedge /if no edgesreturn row/has no successors return - /no such vertex /end nosuccessors(deleting vertex is straightforward except for few details the vertex is removed from the vertexlist[arrayand the vertices above it are moved down to fill up the vacant position likewisethe row and column for the vertex are removed from the adjacency matrixand the rows and columns above and to the right are moved down and to the left to fill the vacancies this is carried out by the deletevertex()moverowup()and movecolleft(methodswhich you can examine in the complete listing for topo java it' actually more efficient to use the adjacency-list representation of the graph for this algorithmbut that would take us too far afield the main(routine in this program calls on methodssimilar to those we saw earlierto create the same graph shown in figure the addedge(methodas we notedinserts single number into the adjacency matrix because this is directed graph here' the code for main()public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ad /ae /be /cf /dg /eg |
25,225 | thegraph addedge( )/fh /gh thegraph topo()/do the sort /end main(once the graph is createdmain(calls topo(to sort the graph and display the result here' the outputtopologically sorted orderbaedgcfh of courseyou can rewrite main(to generate other graphs the complete topo java program you've seen most of the routines in topo java already listing shows the complete program listing the topo java program /topo java /demonstrates topological sorting /to run this programc>java topoapp import java awt *///////////////////////////////////////////////////////////////class vertex public char label/label ( ' 'public vertex(char lablabel lab/end class vertex /constructor ///////////////////////////////////////////////////////////////class graph private final int max_verts private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices private char sortedarray[]/public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts for(int = <max_vertsj++/set adjacency |
25,226 | adjmat[ ][ sortedarray new char[max_verts]/end constructor /matrix to /sorted vert labels /public void addvertex(char labvertexlist[nverts++new vertex(lab)/public void addedge(int startint endadjmat[start][end /public void displayvertex(int vsystem out print(vertexlist[vlabel)/public void topo(/toplogical sort int orig_nverts nverts/remember how many verts while(nverts /while vertices remain/get vertex with no successorsor - int currentvertex nosuccessors()if(currentvertex =- /must be cycle system out println("errorgraph has cycles")return/insert vertex label in sorted array (start at endsortedarray[nverts- vertexlist[currentvertexlabeldeletevertex(currentvertex)/end while /delete vertex /vertices all gonedisplay sortedarray system out print("topologically sorted order")for(int = <orig_nvertsj++system out printsortedarray[ )system out println("")/end topo |
25,227 | successors /(or - if no such vertsboolean isedge/edge from row to column in adjmat for(int row= row<nvertsrow++/for each vertexisedge false/check edges for(int col= col<nvertscol++ifadjmat[row][col /if edge to /anotherisedge truebreak/this vertex /has successor /try another if!isedge /if no edgesreturn row/has no successors return - /no such vertex /end nosuccessors(/public void deletevertex(int delvertif(delvert !nverts- /if not last vertex/delete from vertexlist for(int =delvertj<nverts- ++vertexlist[jvertexlist[ + ]/delete row from adjmat for(int row=delvertrow<nverts- row++moverowup(rownverts)/delete col from adjmat for(int col=delvertcol<nverts- col++movecolleft(colnverts- )nverts--/one less vertex /end deletevertex /private void moverowup(int rowint lengthfor(int col= col<lengthcol++adjmat[row][coladjmat[row+ ][col]/private void movecolleft(int colint lengthfor(int row= row<lengthrow++ |
25,228 | //end class graph ///////////////////////////////////////////////////////////////class topoapp public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ad /ae /be /cf /dg /eg /fh /gh thegraph topo()/end main(/end class topoapp /do the sort ///////////////////////////////////////////////////////////////in the next we'll see what happens when edges are given weight as well as direction summary graphs consist of vertices connected by edges graphs can represent many real-world entitiesincluding airline routeselectrical circuitsand job scheduling search algorithms allow you to visit each vertex in graph in systematic way searches are the basis of several other activities the two main search algorithms are depth-first search (dfsand breadth-first search (bfs |
25,229 | algorithm can be based on queue minimum spanning tree (mstconsists of the minimum number of edges necessary to connect all graph' vertices slight modification of the depth-first search algorithm on an unweighted graph yields its minimum spanning tree in directed graphedges have direction (often indicated by an arrowa topological sorting algorithm creates list of vertices arranged so that vertex precedes vertex in the list if there' path from to topological sort can be carried out only on daga directedacyclic (no cyclesgraph topological sorting is typically used for scheduling complex projects that consist of tasks contingent on other tasks weighted graphs overview in the last we saw that graph' edges can have direction in this we'll explore another edge featureweight for exampleif vertices in weighted graph represent citiesthe weight of the edges might represent distances between the citiesor costs to fly between themor the number of automobile trips made annually between them ( figure of interest to highway engineerswhen we include weight as feature of graph' edgessome interesting and complex questions arise what is the minimum spanning tree for weighted graphwhat is the shortest (or cheapestdistance from one vertex to anothersuch questions have important applications in the real world we'll first examine weighted but non-directed graph and its minimum spanning tree in the second half of this we'll examine graphs that are both directed and weightedin connection with the famous dijkstra' algorithmused to find the shortest path from one vertex to another minimum spanning tree with weighted graphs to introduce weighted graphs we'll return to the question of the minimum spanning tree creating such tree is bit more complicated with weighted graph than with an unweighted one when all edges are the same length it' fairly straightforward--as we saw in the last -for the algorithm to choose one to add to the minimum spanning tree but when edges can have different weightssome arithmetic is needed to choose the right one an examplecable tv in the jungle suppose we want to install cable television line that connects six towns in the mythical country of magnaguena five links will connect the six citiesbut which five links should they bethe cost of connecting each pair of cities variesso we must pick the route carefully to minimize the overall cost figure shows weighted graph with verticesrepresenting the towns ajobordocolinadanzaerizoand flor each edge has weightshown by number alongside |
25,230 | dollarsof installing cable link between two cities (notice that some links are impractical because of distance or terrainfor examplewe will assume that it' too far from ajo to colina or from danza to florso these links don' need to be considered and don' appear on the graph figure weighted graph how can we pick route that minimizes the cost of installing the cable systemthe answer is to calculate minimum spanning tree it will have five links (one fewer than the number of towns)it will connect all six townsand it will minimize the total cost of building these links can you figure out this route by looking at the graph in figure if notyou can solve the problem with the graphw workshop applet the graphw workshop applet the graphw workshop applet is similar to graphn and graphdbut it creates weightedundirected graphs before you drag from vertex to vertex to create an edgeyou must type the weight of the edge into the text box in the upper-right corner this applet carries out only one algorithmwhen you repeatedly click the tree buttonit finds the minimum spanning tree for whatever graph you have created the new and view buttons work as in previous graph applets to erase an old graph and to view the adjacency matrix try out this applet by creating some small graphs and finding their minimum spanning trees (for some configurations you'll need to be careful positioning the vertices so that the weight numbers don' fall on top of each other as you step through the algorithm you'll see that vertices acquire red bordersand edges are made thickerwhen they're added to the minimum spanning tree vertices that are in the tree are also listed below the graphon the left on the rightthe contents of priority queue (pqis shown the items in the priority queue are edges for instancethe entry ab in the queue is the edge from to bwhich has weight of we'll explain what the priority queue does after we've shown an example of the algorithm use the graphw workshop applet to construct the graph of figure the result should resemble figure |
25,231 | now find this graph' minimum spanning tree by stepping through the algorithm with the tree key the result should be the minimum spanning tree shown in figure figure the minimum spanning tree the applet should discover that the minimum spanning tree consists of the edges adabbeecand cffor total edge weight of the order in which the edges are specified is unimportant if you start at different vertex you will create tree with the same edgesbut in different order send out the surveyors the algorithm for constructing the minimum spanning tree is little involvedso we're going to introduce it using an analogy involving cable tv employees you are one employee-- managerof course--and there are also various surveyors computer algorithm (unless perhaps it' neural networkdoesn' "knowabout all the data in given problem at onceit can' deal with the big picture it must acquire the data little by littlemodifying its view of things as it goes along with graphsalgorithms tend to start at some vertex and work outwardacquiring data about nearby vertices before finding out about vertices farther away we've seen examples of this in the depth-first and breadth-first searches in the last in similar waywe're going to assume that you don' start out knowing the costs of installing the cable tv line between all the pairs of towns in magnaguena acquiring this information takes time that' where the surveyors come in starting in ajo you start by setting up an office in ajo (you could start in any townbut ajo has the best restaurants only two towns are reachable from ajobordo and danza (refer to figure you hire two toughjungle-savvy surveyors and send them out along the dangerous wilderness trailsone to bordo and one to danza their job is to determine the cost of installing cable along these routes the first surveyor arrives in bordohaving completed her surveyand calls you on her cellular phoneshe says it will cost million dollars to install the cable link between ajo and bordo the second surveyorwho has had some trouble with crocodilesreports little later from danza that the ajo-danza linkwhich crosses more level countrywill cost only million dollars you make listajo-danza$ million ajo-bordo$ million you always list the links in order of increasing costwe'll see why this is good idea |
25,232 | building the ajo-danza link at this point you figure you can send out the construction crew to actually install the cable from ajo to danza how can you be sure the ajo-danza route will eventually be part of the cheapest solution (the minimum spanning tree)so faryou only know the cost of two links in the system don' you need more informationto get feel for this situationtry to imagine some other route linking ajo to danza that would be cheaper than the direct link if it doesn' go directly to danzathis other route must go through bordo and circle back to danzapossibly via one or more other towns but you already know the link to bordo is more expensiveat million dollars,than the link to danzaat so even if the remaining links in this hypothetical circle route are cheapas shown in figure it will still be more expensive to get to danza by going through bordo alsoit will be more expensive to get to towns on the circle routelike xby going through bordo than by going through danza figure hypothetical circle route we conclude that the ajo-danza route will be part of the minimum spanning tree this isn' formal proof (which is beyond the scope of this book)but it does suggest your best bet is to pick the cheapest link so you build the ajo-danza link and install an office in danza why do you need an officedue to magnaguena government regulationyou must install an office in town before you can send out surveyors from that town to adjacent towns in graph termsyou must add vertex to the tree before you can learn the weight of the edges leading away from that vertex all towns with offices are connected by cable with each othertowns with no offices are not yet connected building the ajo-bordo link once you've completed the ajo-danza link and built your office in danzayou can send out surveyors from danza to all the towns reachable from there these are bordocolinaand erizo the surveyors reach their destinations and report back costs of and million dollarsrespectively (of course you don' send surveyor to ajo because you've already surveyed the ajo-danza route and installed its cable now you know the costs of four links from towns with offices to towns with no officesajo-bordo$ million danza-bordo$ million danza-colina$ million danza-erizo$ million |
25,233 | therethere' no point giving any further consideration to this link the route on which cable has just been installed is always removed from the list at this point it may not be obvious what to do next there are many potential links to choose from what do you imagine is the best strategy nowhere' the ruleremember rulefrom the listalways pick the cheapest edge actuallyyou already followed this rule when you chose which route to follow from ajothe ajo-danza edge was the cheapest here the cheapest edge is ajo-bordoso you install cable link from ajo to bordo for cost of million dollarsand build an office in bordo let' pause for moment and make general observation at given time in the cable system constructionthere are three kinds of towns towns that have offices and are linked by cable (in graph terms they're in the minimum spanning tree towns that aren' linked yet and have no officebut for which you know the cost to link them to at least one town with an office we can call these "fringetowns towns you don' know anything about at this stageajodanzaand bordo are in category colina and erizo are in category and flor is in category as shown in figure as we work our way through the algorithmtowns move from category to and from to figure partway through the minimum spanning tree algorithm building the bordo-erizo link at this pointajodanzaand bordo are connected to the cable system and have offices you already know the costs from ajo and danza to towns in category but you don' know these costs from bordo so from bordo you send out surveyors to colina and erizo they report back costs of to colina and to erizo here' the new listbordo-erizo$ million danza-colina$ million bordo-colina$ million danza-erizo$ million |
25,234 | notedthere' no point in considering links to towns that are already connectedeven by an indirect route from this list we can see that the cheapest route is bordo-erizoat million dollars you send out the crew to install this cable linkand you build an office in erizo (refer to figure building the erizo-colina link from erizo the surveyors report back costs of to colina and to flor the danza-erizo link from the previous list must be removed because erizo is now connected town your new list is erizo-colina$ million erizo-flor$ million danza-colina$ million bordo-colina$ million the cheapest of these links is erizo-colinaso you built this link and install an office in colina andfinallythe colina-flor link the choices are narrowing after removing already linked townsyour list now shows only colina-flor$ million erizo-flor$ million you install the last link of cable from colina to florbuild an office in florand you're done you know you're done because there' now an office in every town you've constructed the cable route ajo-danzaajo-bordobordo-erizoerizo-colinaand colina-floras shown earlier in figure this is the cheapest possible route linking the six towns of magnaguena creating the algorithm using the somewhat fanciful idea of installing cable tv systemwe've shown the main ideas behind the minimum spanning tree for weighted graphs now let' see how we' go about creating the algorithm for this process the priority queue the key activity in carrying out the algorithmas described in the cable tv examplewas maintaining list of the costs of links between pairs of cities we decided where to build the next link by selecting the minimum of these costs list in which we repeatedly select the minimum value suggests priority queue as an appropriate data structureand in fact this turns out to be an efficient way to handle the minimum spanning tree problem instead of list or arraywe use priority queue in serious program this priority queue might be based on heapas described in "heaps this would speed up operations on large priority queues howeverin our |
25,235 | outline of the algorithm let' restate the algorithm in graph terms (as opposed to cable tv terms)start with vertexput it in the tree then repeatedly do the following find all the edges from the newest vertex to other vertices that aren' in the tree put these edges in the priority queue pick the edge with the lowest weightand add this edge and its destination vertex to the tree do these steps until all the vertices are in the tree at that pointyou're done in step "newestmeans most recently installed in the tree the edges for this step can be found in the adjacency matrix after step the list will contain all the edges from vertices in the tree to vertices on the fringe extraneous edges in maintaining the list of linkswe went to some trouble to remove links that led to town that had recently become connected if we didn' do thiswe would have ended up installing unnecessary cable links in programming algorithm we must likewise make sure that we don' have any edges in the priority queue that lead to vertices that are already in the tree we could go through the queue looking for and removing any such edges each time we added new vertex to the tree as it turns outit is easier to keep only one edge from the tree to given fringe vertex in the priority queue at any given time that isthe queue should contain only one edge to each category vertex you'll see that this is what happens in the graphw workshop applet there are fewer edges in the priority queue than you might expectjust one entry for each category vertex step through the minimum spanning tree for figure and verify that this is what happens table shows how edges with duplicate destinations have been removed from the priority queue table edge pruning step number unpruned edge list pruned edge list (in priorityqueue ab ad ab ad de dc db ab de dc ab db (ab de bc dc be dc be de (be )bc (dc duplicate removed from priority queue |
25,236 | bc dc ef ec ef ec bc (ec )dc (ec ef cf cf ef remember that an edge consists of letter for the source (startingvertex of the edgea letter for the destination (ending vertex)and number for the weight the second column in this table corresponds to the lists you kept when constructing the cable tv system it shows all edges from category vertices (those in the treeto category vertices (those with at least one known edge from category vertexthe third column is what you see in the priority queue when you run the graphw applet any edge with the same destination vertex as another edgeand which has greater weighthas been removed the fourth column shows the edges that have been removedandin parenthesesthe edge with the smaller weight that superseded it and remains in the queue remember that as you go from step to step the last entry on the list is always removed because this edge is added to the tree looking for duplicates in the priority queue how do we make sure there is only one edge per category vertexeach time we add an edge to the queuewe make sure there' no other edge going to the same destination if there iswe keep only the one with the smallest weight this necessitates looking through the priority queue item by itemto see if there' such duplicate edge priority queues are not designed for random accessso this is not an efficient activity howeverviolating the spirit of the priority queue is necessary in this situation java code the method that creates the minimum spanning tree for weighted graphmstw()follows the algorithm outlined above as in our other graph programsit assumes there' list of vertices in vertexlist[]and that it will start with the vertex at index the currentvert variable represents the vertex most recently added to the tree here' the code for mstw()public void mstw(currentvert /minimum spanning tree /start at while(ntree nverts- /while not all verts in tree /put currentvert in tree vertexlist[currentvertisintree truentree++/insert edges adjacent to currentvert into pq for(int = <nvertsj++/for each vertexif( ==currentvert/skip if it' us continueif(vertexlist[jisintree/skip if in the tree |
25,237 | int distance adjmat[currentvert][ ]ifdistance =infinity/skip if no edge continueputinpq(jdistance)/put it in pq (maybeif(thepq size()== /no vertices in pqsystem out println(graph not connected")return/remove edge with minimum distancefrom pq edge theedge thepq removemin()int sourcevert theedge srcvertcurrentvert theedge destvert/display edge from source to current system out printvertexlist[sourcevertlabel )system out printvertexlist[currentvertlabel )system out print(")/end while(not all verts in tree/mst is complete for(int = <nvertsj++/unmark vertices vertexlist[jisintree false/end mstw(the algorithm is carried out in the while loopwhich terminates when all vertices are in the tree within this loop the following activities take place the current vertex is placed in the tree the edges adjacent to this vertex are placed in the priority queue (if appropriate the edge with the minimum weight is removed from priority queue the destination vertex of this edge becomes the current vertex let' look at these steps in more detail in step the currentvert is placed in the tree by marking its isintree field in step the edges adjacent to this vertex are considered for insertion in the priority queue the edges are examined by scanning across the row whose number is currentvert in the adjacency matrix an edge is placed in the queue unless one of these conditions is truethe source and destination vertices are the same the destination vertex is in the tree there is no edge to this destination if none of these conditions is truethe putinpq(method is called to put the edge in the priority queue actuallythis routine doesn' always put the edge in the queue eitheras |
25,238 | in step the edge with the minimum weight is removed from the priority queue this edge and its destination vertex are added to the treeand the source vertex (currentvertand destination vertex are displayed at the end of mstw()the vertices are removed from the tree by resetting their isintree variables that isn' strictly necessary in this programbecause only one tree is created from the data howeverit' good housekeeping to restore the data to its original form when you finish with it as we notedthe priority queue should contain only one edge with given destination vertex the putinpq(method makes sure this is true it calls the find(method of the priorityq classwhich has been doctored to find the edge with specified destination vertex if there is no such vertexand find(therefore returns - then putinpq(simply inserts the edge into the priority queue howeverif such an edge does existputinpq(checks to see whether the existing edge or the new proposed edge has the lower weight if it' the old edgeno change is necessary if the new one has lower weightthe old edge is removed from the queue and the new one is installed here' the code for putinpq()public void putinpq(int newvertint newdist/is there another edge with the same destination vertexint queueindex thepq find(newvert)/got edge' index if(queueindex !- /if there is one/get edge edge tempedge thepq peekn(queueindex)int olddist tempedge distanceif(olddist newdist/if new edge shorterthepq removen(queueindex)/remove old edge edge theedge new edge(currentvertnewvertnewdist)thepq insert(theedge)/insert new edge /else no actionjust leave the old vertex there /end if else /no edge with same destination vertex /so insert new one edge theedge new edge(currentvertnewvertnewdist)thepq insert(theedge)/end putinpq(the mstw java program the priorityq class uses an array to hold the members as we notedin program dealing with large graphs heap would be more appropriate than the array shown here the priorityq class has been augmented with various methods it canas we've seenfind an edge with given destination vertex with find(it can also peek at an arbitrary member with peekn(and remove an arbitrary member with removen(most of the rest of this program you've seen before listing shows the complete mstw java program |
25,239 | /mstw java /demonstrates minimum spanning tree with weighted graphs /to run this programc>java mstwapp import java awt *///////////////////////////////////////////////////////////////class edge public int srcvert/index of vertex starting edge public int destvert/index of vertex ending edge public int distance/distance from src to dest public edge(int svint dvint dsrcvert svdestvert dvdistance /end class edge /constructor ///////////////////////////////////////////////////////////////class priorityq /array in sorted orderfrom max at to min at size- private final int size private edge[quearrayprivate int sizepublic priorityq(/constructor quearray new edge[size]size public void insert(edge itemorder int /insert item in sorted for( = <sizej++/find place to insert ifitem distance >quearray[jdistance breakfor(int =size- >=jk--/move items up quearray[ + quearray[ ]quearray[jitemsize++public edge removemin(/insert item /remove minimum item |
25,240 | public void removen(int /remove item at for(int =nj<size- ++/move items down quearray[jquearray[ + ]size--public edge peekmin(/peek at minimum item return quearray[size- ]public int size(return size/return number of items public boolean isempty(return (size== )/true if queue is empty public edge peekn(int nreturn quearray[ ]/peek at item public int find(int finddex/find item with specified /destvert value for(int = <sizej++if(quearray[jdestvert =finddexreturn jreturn - /end class priorityq ///////////////////////////////////////////////////////////////class vertex public char labelpublic boolean isintree/label ( ' '/public vertex(char lab/constructor label labisintree false//end class vertex ///////////////////////////////////////////////////////////////class graph |
25,241 | private final int infinity private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices private int currentvertprivate priorityq thepqprivate int ntree/number of verts in tree /public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix to adjmat[ ][kinfinitythepq new priorityq()/end constructor /public void addvertex(char labvertexlist[nverts++new vertex(lab)/public void addedge(int startint endint weightadjmat[start][endweightadjmat[end][startweight/public void displayvertex(int vsystem out print(vertexlist[vlabel)/public void mstw(/minimum spanning tree currentvert /start at while(ntree nverts- /while not all verts in tree /put currentvert in tree vertexlist[currentvertisintree true |
25,242 | /insert edges adjacent to currentvert into pq for(int = <nvertsj++/for each vertexif( ==currentvert/skip if it' us continueif(vertexlist[jisintree/skip if in the tree continueint distance adjmat[currentvert][ ]ifdistance =infinity/skip if no edge continueputinpq(jdistance)/put it in pq (maybeif(thepq size()== /no vertices in pqsystem out println(graph not connected")return/remove edge with minimum distancefrom pq edge theedge thepq removemin()int sourcevert theedge srcvertcurrentvert theedge destvert/display edge from source to current system out printvertexlist[sourcevertlabel )system out printvertexlist[currentvertlabel )system out print(")/end while(not all verts in tree/mst is complete for(int = <nvertsj++/unmark vertices vertexlist[jisintree false/end mstw /public void putinpq(int newvertint newdist/is there another edge with the same destination vertexint queueindex thepq find(newvert)if(queueindex !- /got edge' index edge tempedge thepq peekn(queueindex)/get edge int olddist tempedge distanceif(olddist newdist/if new edge shorterthepq removen(queueindex)/remove old edge edge theedge new edge(currentvertnewvertnewdist)thepq insert(theedge)/insert new edge |
25,243 | /else no actionjust leave the old vertex there /end if else /no edge with same destination vertex /so insert new one edge theedge new edge(currentvertnewvertnewdist)thepq insert(theedge)/end putinpq(//end class graph ///////////////////////////////////////////////////////////////class mstwapp public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ (start for mstthegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )/ab thegraph addedge( )/ad thegraph addedge( )/bc thegraph addedge( )/bd thegraph addedge( )/be thegraph addedge( )/cd thegraph addedge( )/ce thegraph addedge( )/cf thegraph addedge( )/de thegraph addedge( )/ef system out print("minimum spanning tree")thegraph mstw()/minimum spanning tree system out println()/end main(/end class mstwapp //////////////////////////////////////////////////////////////the main(routine in class mstwapp creates the tree in figure here' the outputminimum spanning treead ab be ec cf the shortest-path problem |
25,244 | that of finding the shortest path between two given vertices the solution to this problem is applicable to wide variety of real-world situationsfrom the layout of printed circuit boards to project scheduling it is more complex problem than we've seen beforeso let' start by looking at (somewhatreal-world scenario in the same mythical country of magnaguena introduced in the last section the railroad line this time we're concerned with railroads rather than cable tv howeverthis project is not as ambitious as the last one we're not going to build the railroadit already exists we just want to find the cheapest route from one city to another the railroad charges passengers fixed fare to travel between any two towns these fares are shown in figure that isfrom ajo to bordo is $ from bordo to danza is $ and so on these rates are the same whether the ride between two towns is part of longer itinerary or not (unlike the situation with today' airline faresthe edges in figure are directed they represent single-track railroad lineson which (in the interest of safetytravel is permitted in only one direction for exampleyou can go directly from ajo to bordobut not from bordo to ajo figure train fares in magnaguena although in this situation we're interested in the cheapest faresthe graph problem is nevertheless always referred to as the shortest path problem here shortest doesn' necessarily mean shortest in terms of distanceit can also mean cheapestfastestor best route by some other measure cheapest fares there are several possible routes between any two towns for exampleto take the train from ajo to erizo you could go through danzaor you could go through bordo and colinaor through danza and colinaor you could take several other routes (it' not possible to reach the town of flor by rail because it lies beyond the rugged sierra descaro rangeso it doesn' appear on the graph this is fortunatebecause it reduces the size of certain lists we'll need to make the shortest-path problem isfor given starting point and destinationwhat' the cheapest routein figure you can see (with little mental effortthat the cheapest route from ajo to erizo passes through danza and colinait will cost you $ directedweighted graph as we notedour railroad has only single-track linesso you can go in only one direction between any two cities this corresponds to directed graph we could have portrayed the more realistic situation in which you can go either way between two cities for the same pricethis would correspond to nondirected graph howeverthe |
25,245 | directed graph dijkstra' algorithm the solution we'll show for the shortest-path problem is called dijkstra' algorithmafter edsger dijkstrawho first described it in this algorithm is based on the adjacency matrix representation of graph somewhat surprisinglyit finds not only the shortest path from one specified vertex to anotherbut the shortest paths from the specified vertex to all the other vertices agents and train rides to see how dijkstra' algorithm worksimagine that you want to find the cheapest way to travel from ajo to all the other towns in magnaguena you (and various agents you will hireare going to play the role of the computer program carrying out dijkstra' algorithm of course in real life you could probably obtain schedule from the railroad with all the fares the algorithmhowevermust look at one piece of information at timeso (as in the last sectionwe'll assume that you are similarly unable to see the big picture at each townthe stationmaster can tell you how much it will cost to travel to the other towns that you can reach directly (that isin single ridewithout passing through another townalashe cannot tell you the fares to towns further than one ride away you keep notebookwith column for each town you hope to end up with each column showing the cheapest route from your starting point to that town the first agentin ajo eventually you're going to place an agent in every townthis agent' job is to obtain information about ticket costs to other towns you yourself are the agent in ajo all the stationmaster in ajo can tell you is that it will cost $ to ride to bordoand $ to ride to danza you write this in your notebookas shown in table table step an agent at ajo from ajo to bordo colina danza erizo step (via ajoinf (via ajoinf the entry "infis short for "infinity,and means that you can' get from ajo to the town shown in the column heador at least that you don' yet know how to get there (in the algorithm infinity will be represented by very large numberwhich will help with calculationsas we'll see the entries in the table in parentheses are the last town visited before you arrive at the various destinations we'll see later why this is good to know what do you do nowhere' the rule you'll followremember rulealways send an agent to the town whose overall fare from the starting point (ajois the cheapest |
25,246 | as that used in the minimum spanning tree problem (the cable tv installationthereyou picked the least expensive single link (edgefrom the connected towns to an unconnected town hereyou pick the least expensive total route from ajo to town with no agent in this particular point in your investigation these two approaches amount to the same thingbecause all known routes from ajo consist of only one edgebut as you send agents to more townsthe routes from ajo will become the sum of several direct edges the second agentin bordo the cheapest fare from ajo is to bordoat $ so you hire passerby and send him to bordowhere he'll be your agent once he' therehe calls you by telephoneand tells you that the bordo stationmaster says it costs $ to ride to colina and $ to danza doing some quick arithmeticyou figure it must be $ plus $ or $ to go from ajo to colina via bordoso you modify the entry for colina you also can see thatgoing via bordoit must be $ plus $ or $ from ajo to danza however--and this is key point--you already know it' only $ going directly from ajo to danza you only care about the cheapest route from ajoso you ignore the more expensive routeleaving this entry as it was the resulting notebook entries are shown in the last row in table figure shows the situation geographically table step agents at ajo and bordo from ajo to bordo colina danza erizo step (via ajoinf (via ajoinf step (via ajo) (via bordo (via ajoinf figure following step in the shortest-path algorithm once we've installed an agent in townwe can be sure that the route taken by the agent to get to that town is the cheapest route whyconsider the present case if there were cheaper route than the direct one from ajo to bordoit would need to go through some other town but the only other way out of ajo is to danzaand that ride is already more expensive than the direct route to bordo adding additional fares to get from danza |
25,247 | from this we decide that from now on we won' need to update the entry for the cheapest fare from ajo to bordo this fare will not changeno matter what we find out about other towns we'll put an next to it to show that there' an agent in the town and that the cheapest fare to it is fixed three kinds of town as in the minimum spanning tree algorithmwe're dividing the towns into three categories towns in which we've installed an agentthey're in the tree towns with known fares from towns with an agentthey're on the fringe unknown towns at this point ajo and bordo are category towns because there are agents there category towns form tree consisting of paths that all begin at the starting vertex and that each end on different destination vertex (this is not the same treeof courseas minimum spanning tree some other towns have no agentsbut you know the fares to them because you have agents in adjacent category towns you know the fare from ajo to danza is $ and from bordo to colina is $ because the fares to them are knowndanza and colina are category (fringetowns you don' know anything yet about erizoit' an "unknowntown figure shows these categories at the current point in the algorithm as in the minimum spanning tree algorithmthe algorithm moves towns from the unknown category to the fringe categoryand from the fringe category to the treeas it goes along the third agentin danza at this pointthe cheapest route you know that goes from ajo to any town without an agent is $ the direct route from ajo to danza both the ajo-bordo-colina route at $ and the ajo-bordo-danza route at $ are more expensive you hire another passerby and send her to danza with an $ ticket she reports that from danza it' $ to colina and $ to erizo now you can modify your entry for colina beforeit was $ from ajogoing via bordo now you see you can reach colina for only $ going via danza alsoyou now know fare from ajo to the previously unknown erizoit' $ via danza you note these changesas shown in table and figure table step agents at ajobordoand danza from ajo to bordo colina danza erizo |
25,248 | (via ajoinf (via ajoinf step (via ajo) (via bordo (via ajoinf step (via ajo) (via danza (via ajo) (via danzafigure following step in the shortest-path algorithm the fourth agentin colina now the cheapest path to any town without an agent is the $ trip from ajo to colinagoing via danza accordinglyyou dispatch an agent over this route to colina he reports that it' $ from there to erizo now you can calculate thatbecause colina is $ from ajo (via danza)and erizo is $ from colinayou can reduce the minimum ajo-to-erizo fare from $ (the ajo-danza-erizo routeto $ (the ajo-danza-colina-erizo routeyou update your notebook accordinglyas shown in table and figure table step agents in ajobordodanzaand colina from ajo to bordo colina danza erizo step (via ajoinf (via ajoinf step (via ajo) (via bordo (via ajoinf step (via ajo) (via danza (via ajo) (via danzastep (via ajo) (via danza) (via ajo) (via colina |
25,249 | the last agentin erizo the cheapest path from ajo to any town you know about that doesn' have an agent is now $ to erizovia danza and colina you dispatch an agent to erizobut she reports that there are no routes from erizo to towns without agents (there' route to bordobut bordo has an agent table shows the final line in your notebookall you've done is add star to the erizo entry to show there' an agent there table step agents in ajobordodanzacolinaand erizo from ajo to bordo colina danza erizo step (via ajoinf (via ajoinf step (via ajo) (via bordo (via ajoinf step (via ajo) (via danza (via ajo) (via danzastep (via ajo) (via danza) (via ajo) (via colinastep (via ajo) (via danza) (via ajo) (via colina)when there' an agent in every townyou know the fares from ajo to every other town so you're done with no further calculationsthe last line in your notebook shows the cheapest routes from ajo to all other towns this narrative has demonstrated the essentials of dijkstra' algorithm the key points are each time you send an agent to new townyou use the new information provided by that agent to revise your list of fares only the cheapest fare (that you know aboutfrom the starting point to given town is retained you always send the new agent to the town that has the cheapest path from the starting point (not the cheapest edge from any town with an agentas in the minimum |
25,250 | using the workshop applet let' see how this looks using the graphdw (for directed and weightedworkshop applet use the applet to create the graph from figure the result should look something like figure (we'll see how to make the table appear below the graph in moment this is weighteddirected graphso to make an edgeyou must type number before draggingand you must drag in the correct directionfrom the start to the destination figure the railroad scenario in graphdw when the graph is completeclick the path buttonand when promptedclick the vertex few more clicks on path will place in the treeshown with red circle around the shortest-path array an additional click will install table under the graphas you can see in figure the corresponding message near the top of the figure is copied row from adjacency matrix to shortest-path array dijkstra' algorithm starts by copying the appropriate row of the adjacency matrix (that isthe row for the starting vertexto an array (remember that you can examine the adjacency matrix at any time by pressing the view button this array is called the "shortest-patharray it corresponds to the most recent row of notebook entries you made while determining the cheapest train fares in magnaguena this array will hold the current versions of the shortest paths to the other verticeswhich we can call the destination vertices these destination vertices are represented by the column heads in the table table step the shortest-path array inf( (ainf( (ainf( |
25,251 | enclosed in parentheses the parent is the vertex you reached just before you reached the destination vertex in this case the parents are all because we've only moved one edge away from if fare is unknown (or meaninglessas from to ait' shown as infinityrepresented by "inf,as in the rail-fare notebook entries notice that the column heads of those vertices that have already been added to the tree are shown in red the entries for these columns won' change minimum distance initiallythe algorithm knows the distances from to other vertices that are exactly one edge from only and are adjacent to aso they're the only ones whose distances are shown the algorithm picks the minimum distance another click on path will show you the message minimum distance from is to vertex the algorithm adds this vertex to the treeso the next click will show you added vertex to tree now is circled in the graphand the column head is in red the edge from to is made darker to show it' also part of the tree column by column in the shortest-path array now the algorithm knowsnot only all the edges from abut the edges from as well so it goes through the shortest-path arraycolumn by columnchecking whether shorter path than that shown can be calculated using this new information vertices that are already in the treehere and bare skipped first column is examined you'll see the message to ca to ( plus edge bc ( less than to (infthe algorithm has found shorter path to than that shown in the array the array shows infinity in the column but from to is (which the algorithm finds in the column in the shortest-path arrayand from to is (which it finds in row column in the adjacency matrixthe sum is the distance is less than infinityso the algorithm updates the shortest-path array for column cinserting this is followed by in parenthesesbecause that' the last vertex before reaching cb is the parent of next the column is examined you'll see the message to da to ( plus edge bd ( greater than or equal to to ( the algorithm is comparing the previously shown distance from to dwhich is (the direct route)with possible route via (that isa- -dbut path - is and edge bd is so the sum is this is bigger than so is not changed |
25,252 | to ea to ( plus edge be (infgreater than or equal to to (infthe newly calculated route from to via ( plus infinityis still greater than or equal to the current one in the array (infinity)so the column is not changed the shortestpath array now looks like table table step the shortest-path array inf( ( ( (ainf(anow we can see more clearly the role played by the parent vertex shown in parentheses after each distance each column shows the distance from to an ending vertex the parent is the immediate predecessor of the ending vertex along the path from in column cthe parent vertex is bmeaning that the shortest path from to passes through just before it gets to this information is used by the algorithm to place the appropriate edge in the tree (when the distance is infinitythe parent vertex is meaningless and is shown as new minimum distance now that the shortest-path array has been updatedthe algorithm finds the shortest distance in the arrayas you will see with another path key press the message is minimum distance from is to vertex accordinglythe message added vertex to tree appears and the new vertex and edge ac are added to the tree do it againand again now the algorithm goes through the shortest-path array againchecking and updating the distances for destination vertices not in the treeonly and are still in this category column and are both updated the result is shown in table table step the shortest-path array |
25,253 | inf( ( ( ( (dthe shortest path from to non-tree vertex is to vertex cso is added to the tree next time through the shortest-path arrayonly the distance to is considered it can be shortened by going via cso we have the entries shown in table table step the shortest-path array inf( ( ( ( (cnow the last vertexeis added to the treeand you're done the shortest-path array shows the shortest distances from to all the other vertices the tree consists of all the vertices and the edges abaddcand ceshown with thick lines you can work backward to reconstruct the sequence of vertices along the shortest path to any vertex for the shortest path to efor examplethe parent of eshown in the array in parenthesesis the predecessor of cagain from the arrayis dand the predecessor of is so the shortest path from to follows the route - - - experiment with other graphs using graphdwstarting with small ones you'll find that after while you can predict what the algorithm is going to doand you'll be on your way to understanding dijkstra' algorithm java code the code for the shortest-path algorithm is among the most complex in this bookbut even so it' not beyond mere mortals we'll look first at helper class and then at the chief method that executes the algorithmpath()and finally at two methods called by path(to carry out specialized tasks the spath array and the distpar class as we've seenthe key data structure in the shortest-path algorithm is an array that keeps track of the minimum distances from the starting vertex to the other vertices (destination verticesduring the execution of the algorithm these distances are changeduntil at the end they hold the actual shortest distances from the start in the example codethis array is called spath[(for shortest pathsas we've seenit' important to record not only the minimum distance from the starting |
25,254 | need not be explicitly stored it' only necessary to store the parent of the destination vertex the parent is the vertex reached just before the destination we've seen this in the workshop appletwhereif (dappears in the columnit means that the cheapest path from to is and is the last vertex before on this path there are several ways to keep track of the parent vertexbut we choose to combine the parent with the distance and put the resulting object into the spath[array we call this class of objects distpar (for distance-parentclass distpar /distance and parent /items stored in spath array public int distance/distance from start to this vertex public int parentvert/current parent of this vertex public distpar(int pvint ddistance dparentvert pv/constructor the path(method the path(method carries out the actual shortest-path algorithm it uses the distpar class and the vertex classwhich we saw in the mstw java program earlier in this the path(method is member of the graph classwhich we also saw in mstw java in somewhat different version public void path(/find all shortest paths int starttree /start at vertex vertexlist[starttreeisintree truentree /put it in tree /transfer row of distances from adjmat to spath for(int = <nvertsj++int tempdist adjmat[starttree][ ]spath[jnew distpar(starttreetempdist)/until all vertices are in the tree while(ntree nvertsint indexmin getmin()/get minimum from spath int mindist spath[indexmindistanceif(mindist =infinity/if all infinite /or in treesystem out println("there are unreachable vertices")break/spath is complete |
25,255 | /reset currentvert currentvert indexmin/to closest vert starttocurrent spath[indexmindistance/minimum distance from starttree is /to currentvertand is starttocurrent /put current vertex in tree vertexlist[currentvertisintree truentree++adjust_spath()/update spath[array /end while(ntree<nvertsdisplaypaths()/display spath[contents ntree /clear tree for(int = <nvertsj++vertexlist[jisintree false/end path(the starting vertex is always at index of the vertexlist[array the first task in path(is to put this vertex into the tree as the algorithm proceeds we'll be moving other vertices into the tree as well the vertex class contains flag that indicates whether vertex object is in the tree putting vertex in the tree consists of setting this flag and incrementing ntreewhich counts how many vertices are in the tree secondpath(copies the distances from the appropriate row of the adjacency matrix to spath[this is always row because for simplicity we assume is the index of the starting vertex initiallythe parent field of all the spath[entries is athe starting vertex we now enter the main while loop of the algorithm this loop terminates when all the vertices have been placed in the tree there are basically three actions in this loop choose the spath[entry with the minimum distance put the corresponding vertex (the column head for this entryin the tree this becomes the "current vertexcurrentvert update all the spath[entries to reflect distances from currentvert if path(finds that the minimum distance is infinityit knows that there are vertices that are unreachable from the starting point whybecause not all the vertices are in the tree (the while loop hasn' terminated)and yet there' no way to get to these extra verticesif there werethere would be non-infinite distance before returningpath(displays the final contents of spath[by calling the displaypaths(method this is the only output from the program alsopath(sets ntree to and removes the isintree flags from all the verticesin case they might be used again by another algorithm (although they aren' in this programfinding the minimum distance with getmin(to find the spath[entry with the minimum distancepath(calls the getmin( |
25,256 | with the column number (the array indexof the entry with the minimum distance public int getmin(/get entry from spath /with minimum distance int mindist infinity/assume large minimum int indexmin for(int = <nvertsj++/for each vertex/if it' in tree and if!vertexlist[jisintree &/smaller than old one spath[jdistance mindist mindist spath[jdistanceindexmin /update minimum /end for return indexmin/return index of minimum /end getmin(we could have used priority queue as the basis for the shortest-path algorithmas we did in the last section to find the minimum spanning tree if we hadthe getmin(method would not have been necessarythe minimum-weight edge would have appeared automatically at the front of the queue howeverthe array approach shown makes it easier to see what' going on updating spath[with adjust_spath(the adjust_spath(method is used to update the spath[entries to reflect new information obtained from the vertex just inserted in the tree when this routine is calledcurrentvert has just been placed in the treeand starttocurrent is the current entry in spath[for this vertex the adjust_spath(method now examines each vertex entry in spath[]using the loop counter column to point to each vertex in turn for each spath[entryprovided the vertex is not in the treeit does three things it adds the distance to the current vertex (already calculated and now in starttocurrentto the edge distance from currentvert to the column vertex we call the result starttofringe it compares starttofringe with the current entry in spath[ if starttofringe is lessit replaces the entry in spath[this is the heart of dijkstra' algorithm it keeps spath[updated with the shortest distances to all the vertices that are currently known here' the code for adjust_spath()public void adjust_spath(/adjust values in shortest-path array spath int column /skip starting vertex while(column nverts/go across columns /if this column' vertex already in treeskip it |
25,257 | column++continue/calculate distance for one spath entry /get edge from currentvert to column int currenttofringe adjmat[currentvert][column]/add distance from start int starttofringe starttocurrent currenttofringe/get distance of current spath entry int spathdist spath[columndistance/compare distance from start with spath entry if(starttofringe spathdist/if shorter/update spath spath[columnparentvert currentvertspath[columndistance starttofringecolumn++/end while(column nverts/end adjust_spath(the main(routine in the path java program creates the tree of figure and displays its shortest-path array here' the codepublic static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ (startthegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ab /ad /bc /bd /ce /dc /de /eb system out println("shortest paths")thegraph path()/shortest paths system out println()/end main(the output of this program is |
25,258 | the path java program listing is the complete code for the path java program its various components were all discussed earlier listing the path java program /path java /demonstrates shortest path with weighteddirected graphs /to run this programc>java pathapp import java awt *///////////////////////////////////////////////////////////////class distpar /distance and parent /items stored in spath array public int distance/distance from start to this vertex public int parentvert/current parent of this vertex public distpar(int pvint ddistance dparentvert pv/end class distpar /constructor //////////////////////////////////////////////////////////////class vertex public char labelpublic boolean isintree/label ( ' '/public vertex(char lab/constructor label labisintree false//end class vertex ///////////////////////////////////////////////////////////////class graph private final int max_verts private final int infinity private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix |
25,259 | private int ntreeprivate distpar spath[]private int currentvertprivate int starttocurrent/current number of vertices /number of verts in tree /array for shortest-path data /current vertex /distance to currentvert /public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts ntree for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix adjmat[ ][kinfinity/to infinity spath new distpar[max_verts]/shortest paths /end constructor /public void addvertex(char labvertexlist[nverts++new vertex(lab)/public void addedge(int startint endint weightadjmat[start][endweight/(directed/public void path(/find all shortest paths int starttree /start at vertex vertexlist[starttreeisintree truentree /put it in tree /transfer row of distances from adjmat to spath for(int = <nvertsj++int tempdist adjmat[starttree][ ]spath[jnew distpar(starttreetempdist)/until all vertices are in the tree while(ntree nvertsint indexmin getmin()/get minimum from spath |
25,260 | if(mindist =infinity/if all infinite /or in treesystem out println("there are unreachable vertices")break/spath is complete else /reset currentvert currentvert indexmin/to closest vert starttocurrent spath[indexmindistance/minimum distance from starttree is /to currentvertand is starttocurrent /put current vertex in tree vertexlist[currentvertisintree truentree++adjust_spath()/update spath[array /end while(ntree<nvertsdisplaypaths()contents /display spath[ntree /clear tree for(int = <nvertsj++vertexlist[jisintree false/end path(/public int getmin(/get entry from spath /with minimum distance int mindist infinity/assume minimum int indexmin for(int = <nvertsj++/for each vertex/if it' in tree and if!vertexlist[jisintree &/smaller than old one spath[jdistance mindist mindist spath[jdistanceindexmin /update minimum /end for return indexmin/return index of minimum /end getmin(/public void adjust_spath(/adjust values in shortest-path array spath |
25,261 | /skip starting vertex while(column nverts/go across columns /if this column' vertex already in treeskip it ifvertexlist[columnisintree column++continue/calculate distance for one spath entry /get edge from currentvert to column int currenttofringe adjmat[currentvert][column]/add distance from start int starttofringe starttocurrent currenttofringe/get distance of current spath entry int spathdist spath[columndistance/compare distance from start with spath entry if(starttofringe spathdist/if shorter/update spath spath[columnparentvert currentvertspath[columndistance starttofringecolumn++/end while(column nverts/end adjust_spath(/public void displaypaths(for(int = <nvertsj++/display contents of spath[system out print(vertexlist[jlabel "=")/bif(spath[jdistance =infinitysystem out print("inf")/inf else system out print(spath[jdistance)/ char parent vertexlistspath[jparentvert labelsystem out print("(parent "")/(asystem out println("")//end class graph ///////////////////////////////////////////////////////////////class pathapp |
25,262 | graph thegraph new graph()thegraph addvertex(' ')/ (startthegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ab /ad /bc /bd /ce /dc /de /eb system out println("shortest paths")thegraph path()/shortest paths system out println()/end main(/end class pathapp ///////////////////////////////////////////////////////////////efficiency so far we haven' discussed the efficiency of the various graph algorithms the issue is complicated by the two ways of representing graphsthe adjacency matrix and adjacency lists if an adjacency matrix is usedthe algorithms we've discussed all require ( timewhere is the number of vertices whyif you analyze the algorithmsyou'll see that they involve examining each vertex onceand for that vertex going across its row in the adjacency matrixlooking at each edge in turn in other wordseach cell of the adjacency matrixwhich has cellsis examined for large matriceso( isn' very good performance if the graph is dense there isn' much we can do about improving this performance (as we noted earlierby dense we mean graph that has many edgesone in which many or most of the cells in the adjacency matrix are filled howevermany graphs are sparsethe opposite of dense there' no clear-cut definition of how many edges graph must have to be described as sparse or densebut if each vertex in large graph is connected by only few edgesthe graph would normally be described as sparse in sparse graphrunning times can be improved by using the adjacency list representation rather than the adjacency matrix this is easy to understandyou don' waste time examining adjacency matrix cells that don' hold edges for unweighted graphs the depth-first search with adjacency lists requires ( +etimewhere is the number of vertices and is the number of edges for weighted graphsboth the minimum spanning tree and the shortest-path algorithm require (( + )logvtime in largesparse graphs these times can represent dramatic improvements over the adjacency |
25,263 | we've used the adjacency matrix approach throughout this you can consult sedgewick (see appendix "further reading"and other writers for examples of graph algorithms using the adjacency list approach summary in weighted graphedges have an associated number called the weightwhich might represent distancescoststimesor other quantities the minimum spanning tree in weighted graph minimizes the weights of the edges necessary to connect all the vertices an algorithm using priority queue can be used to find the minimum spanning tree of weighted graph the minimum spanning tree of weighted graph models real-world situations such as installing utility cables between cities the shortest-path problem in nonweighted graph involves finding the minimum number of edges between two vertices solving the shortest-path problem for weighted graphs yields the path with the minimum total edge weight the shortest-path problem for weighted graphs can be solved with dijkstra' algorithm the algorithms for largesparse graphs generally run much faster if the adjacency list representation of the graph is used rather than the adjacency matrix when to use what overview in this we briefly summarize what we've learned so farwith an eye toward deciding what data structure or algorithm to use in particular situation this comes with the usual caveats of necessity it' very general every realworld situation is uniqueso what we say here may not be the right answer to your problem this is divided into three somewhat arbitrary sectionsgeneral-purpose data structuresarrayslinked liststreesand hash tables specialized data structuresstacksqueuespriority queuesand graphs sorting for detailed information on these topicsrefer to the individual in this book general-purpose data structures if you need to store real-world data such as personnel recordsinventoriescontact listsor sales datayou need general-purpose data structure the structures of this type that we've discussed in this book are arrayslinked liststreesand hash tables we call these general-purpose data structures because they are used to store and retrieve data using |
25,264 | specialized structures such as stackswhich allow access to only certain data itemswhich of these general-purpose data structures is appropriate for given problemfigure shows first approximation to this question howeverthere are many factors besides those shown in the figure for more detailwe'll explore some general considerations firstand then zero in on the individual structures figure relationship of general-purpose data structures speed and algorithms the general-purpose data structures can be roughly arranged in terms of speedarrays and linked lists are slowtrees are fairly fastand hash tables are very fast howeverdon' draw the conclusion from this figure that it' always best to use the fastest structures there' penalty for using them firstthey are--in varying degrees--more complex to program than the array and linked list alsohash tables require you to know in advance about how much data can be storedand they don' use memory very efficiently ordinary binary trees will revert to slow (noperation for ordered dataand balanced treeswhich avoid this problemare difficult to program computers grow faster every year the fast structures come with penaltiesand another development makes the slow structures more attractive every year there' an increase in the cpu and memoryaccess speed of the latest computers moore' law (postulated by gordon moore in specifies that cpu performance will double every months this adds up to an astonishing difference in performance between the earliest computers and those available todayand there' no reason to think this increase will slow down any time soon suppose computer few years ago handled an array of objects in acceptable time nowcomputers are times fasterso an array with , objects can run at the same speed many writers provide estimates of the maximum size you can make data structure before it becomes too slow don' trust these estimates (including those in this booktoday' estimate doesn' apply to tomorrow insteadstart by considering the simple data structures unless it' obvious they'll be too slowcode simple version of an array or linked list and see what happens if it runs in acceptable timelook no further why slave away on balanced treewhen no one would ever notice if you used an array insteadeven if you must deal with thousands or tens of thousands of itemsit' still worthwhile to see how well an array or linked list will handle |
25,265 | revert to more sophisticated data structures references are faster java has an advantage over some languages in the speed with which objects can be manipulatedbecausein most data structuresjava stores only referencesnot actual objects therefore most algorithms will run faster than in languages where actual objects occupy space in data structure in analyzing the algorithms it' not the caseas when objects themselves are storedthat the time to "movean object depends on the size of the object because only reference is movedit doesn' matter how large the object is of course in other languagessuch as ++pointers to objects can be stored instead of the objects themselvesthis has the same effect as using referencesbut the syntax is more complicated libraries libraries of data structures are available commercially in all major programming languages languages themselves may have some structures built in javafor exampleincludes vectorstackand hashtable classes +includes the standard template library (stl)which contains classes for many data structures and algorithms using commercial library may eliminate or at least reduce the programming necessary to create the data structures described in this book when that' the caseusing complex structure such as balanced treeor delicate algorithm such as quicksortbecomes more attractive possibility howeveryou must ensure that the class can be adapted to your particular situation arrays in many situations the array is the first kind of structure you should consider when storing and manipulating data arrays are useful when the amount of data is reasonably small the amount of data is predictable in advance if you have plenty of memoryyou can relax the second conditionjust make the array big enough to handle any foreseeable influx of data if insertion speed is importantuse an unordered array if search speed is importantuse an ordered array with binary search deletion is always slow in arrays because an average of half the items must be moved to fill in the newly vacated cell traversal is fast in an ordered array but not supported in an unordered array vectorssuch as the vector class supplied with javaare arrays that expand themselves when they become too full vectors may work when the amount of data isn' known in advance howeverthere may periodically be significant pause while they enlarge themselves by copying the old data into the new space linked lists consider linked list whenever the amount of data to be stored cannot be predicted in advance or when data will frequently be inserted and deleted the linked list obtains whatever storage it needs as new items are addedso it can expand to fill all of available memoryand there is no need to fill "holesduring deletionas there is in arrays |
25,266 | faster than in an array)solike arrayslinked lists are best used when the amount of data is comparatively small linked list is somewhat more complicated to program than an arraybut is simple compared with tree or hash table binary search trees binary tree is the first structure to consider when arrays and linked lists prove too slow tree provides fast (logninsertionsearchingand deletion traversal is ( )which is the maximum for any data structure (by definitionyou must visit every itemyou can also find the minimum and maximum quicklyand traverse range of items an unbalanced binary tree is much easier to program than balanced treebut unfortunatelyordered data can reduce its performance to (ntimeno better than linked list howeverif you're sure the data will arrive in random orderthere' no point using balanced tree balanced trees of the various kinds of balanced treeswe discussed red-black trees and trees they are both balanced treesand thus guarantee (lognperformance whether the input data is ordered or not howeverthese balanced trees are challenging to programwith the red-black tree being the more difficult they also impose additional memory overheadwhich may or may not be significant the problem of complex programming may be reduced if commercial class can be used for tree in some cases hash table may be better choice than balanced tree hash-table performance doesn' degrade when the data is ordered there are other kinds of balanced treesincluding avl treessplay trees - treesand so onbut they are not as commonly used as the red-black tree hash tables hash tables are the fastest data storage structure this makes them necessity for situations in which computer programrather than humanis interacting with the data hash tables are typically used in spelling checkers and as symbol tables in computer language compilerswhere program must check thousands of words or symbols in fraction of second hash tables may also be useful when personas opposed to computerinitiates dataaccess operations as noted abovehash tables are not sensitive to the order in which data is insertedand so can take the place of balanced tree programming is much simpler than for balanced trees hash tables require additional memoryespecially for open addressing alsothe amount of data to be stored must be known fairly accurately in advancebecause an array is used as the underlying structure hash table with separate chaining is the most robust implementation unless the amount of data is known accurately in advancein which case open addressing offers simpler programming because no linked list class is required hash tables don' support any kind of ordered traversal or access to the minimum or maximum items if these capabilities are importantthe binary search tree is better choice |
25,267 | table summarizes the speeds of the various general-purpose data storage structures using big notation table general-purpose data storage structures data structure search insertion deletion traversal array (no( ( -ordered array (logno(no(no(nlinked list (no( ( -ordered linked list (no(no(no(nbinary tree (averageo(logno(logno(logno(nbinary tree (worst caseo(no(no(no(nbalanced tree (averageand worst caseo(logno(logno(logno(nhash table ( ( ( -insertion in an unordered array is assumed to be at the end of the array the ordered array uses binary searchwhich is fastbut insertion and deletion require moving half the items on the averagewhich is slow traversal implies visiting the data items in order of ascending or descending keysthe -means this operation is not supported special-purpose data structures the special-purpose data structures discussed in this book are the stackthe queueand the priority queue these structuresinstead of supporting database of user-accessible dataare usually used by computer program to aid in carrying out some algorithm we've seen examples of this throughout this booksuch as in "graphs,and "weighted graphs,where stacksqueuesand priority queues are all used in graph algorithms stacksqueuesand priority queues are abstract data types (adtsthat are implemented by more fundamental structure such as an arraylinked listor (in the case of the priority queuea heap these adts present simple interface to the usertypically allowing only insertion and the ability to access or delete only one data item these items are for stacksthe last item inserted for queuesthe first item inserted |
25,268 | these adts can be seen as conceptual aids their functionality could be obtained using the underlying structure (such as an arraydirectlybut the reduced interface they offer simplifies many problems these adts can' be conveniently searched for an item by key value or traversed stack stack is used when you want access only to the last data item insertedit' last-infirst-out (lifostructure stack is often implemented as an array or linked list the array implementation is efficient because the most recently inserted item is placed at the end of the arraywhere it' also easy to delete it stack overflow can occurbut is not likely if the array is reasonably sizedbecause stacks seldom contain huge amounts of data if the stack will contain lot of data and the amount can' be predicted accurately in advance (as when recursion is implemented as stacka linked list is better choice than an array linked list is efficient because items can be inserted and deleted quickly from the head of the list stack overflow can' occur (unless the entire memory is fulla linked list is slightly slower than an array because memory allocation is necessary to create new link for insertionand deallocation of the link is necessary at some point following removal of an item from the list queue queue is used when you want access only to the first data item insertedit' first-infirst-out (fifostructure like stacksqueues can be implemented as arrays or linked lists both are efficient the array requires additional programming to handle the situation in which the queue wraps around at the end of the array linked list must be double-endedto allow insertions at one end and deletions at the other as with stacksthe choice between an array implementation and linked list implementation is determined by how well the amount of data can be predicted use the array if you know about how much data there will beotherwiseuse linked list priority queue priority queue is used when the only access desired is to the data item with the highest priority this is the item with the largest (or sometimes the smallestkey priority queues can be implemented as an ordered array or as heap insertion into an ordered array is slowbut deletion is fast with the heap implementationboth insertion and deletion take (logntime use an array or double-ended linked list if insertion speed is not problem the array works when the amount of data to be stored can be predicted in advancethe linked list when the amount of data is unknown if speed is importanta heap is better choice table special-purpose data-storage structures |
25,269 | insertion deletion comment stack (array or linked ( listo( deletes most recently inserted item queue (array or linked listo( ( deletes least recently inserted item priority queue (ordered arrayo(no( deletes highestpriority item (logndeletes highestpriority item priority queue (heapo(logncomparison of special-purpose structures table shows the big times for stacksqueuesand priority queues these structures don' support searching or traversal special-purpose data structures the special-purpose data structures discussed in this book are the stackthe queueand the priority queue these structuresinstead of supporting database of user-accessible dataare usually used by computer program to aid in carrying out some algorithm we've seen examples of this throughout this booksuch as in "graphs,and "weighted graphs,where stacksqueuesand priority queues are all used in graph algorithms stacksqueuesand priority queues are abstract data types (adtsthat are implemented by more fundamental structure such as an arraylinked listor (in the case of the priority queuea heap these adts present simple interface to the usertypically allowing only insertion and the ability to access or delete only one data item these items are for stacksthe last item inserted for queuesthe first item inserted for priority queuesthe item with the highest priority these adts can be seen as conceptual aids their functionality could be obtained using the underlying structure (such as an arraydirectlybut the reduced interface they offer simplifies many problems these adts can' be conveniently searched for an item by key value or traversed stack stack is used when you want access only to the last data item insertedit' last-infirst-out (lifostructure |
25,270 | efficient because the most recently inserted item is placed at the end of the arraywhere it' also easy to delete it stack overflow can occurbut is not likely if the array is reasonably sizedbecause stacks seldom contain huge amounts of data if the stack will contain lot of data and the amount can' be predicted accurately in advance (as when recursion is implemented as stacka linked list is better choice than an array linked list is efficient because items can be inserted and deleted quickly from the head of the list stack overflow can' occur (unless the entire memory is fulla linked list is slightly slower than an array because memory allocation is necessary to create new link for insertionand deallocation of the link is necessary at some point following removal of an item from the list queue queue is used when you want access only to the first data item insertedit' first-infirst-out (fifostructure like stacksqueues can be implemented as arrays or linked lists both are efficient the array requires additional programming to handle the situation in which the queue wraps around at the end of the array linked list must be double-endedto allow insertions at one end and deletions at the other as with stacksthe choice between an array implementation and linked list implementation is determined by how well the amount of data can be predicted use the array if you know about how much data there will beotherwiseuse linked list priority queue priority queue is used when the only access desired is to the data item with the highest priority this is the item with the largest (or sometimes the smallestkey priority queues can be implemented as an ordered array or as heap insertion into an ordered array is slowbut deletion is fast with the heap implementationboth insertion and deletion take (logntime use an array or double-ended linked list if insertion speed is not problem the array works when the amount of data to be stored can be predicted in advancethe linked list when the amount of data is unknown if speed is importanta heap is better choice table special-purpose data-storage structures data structure insertion deletion comment stack (array or linked ( listo( deletes most recently inserted item queue (array or linked listo( ( deletes least recently inserted item priority queue (no( deletes highest |
25,271 | priority item priority queue (heapo(logno(logndeletes highestpriority item comparison of special-purpose structures table shows the big times for stacksqueuesand priority queues these structures don' support searching or traversal sorting as with the choice of data structuresit' worthwhile initially to try slow but simple sortsuch as the insertion sort it may be that the fast processing speeds available in modern computers will allow sorting of your data in reasonable time (as wild guessthe slow sort might be appropriate for under , items insertion sort is also good for almost-sorted filesoperating in about (ntime if not too many items are out of place this is typically the case where few new items are added to an already sorted file if the insertion sort proves too slowthen the shellsort is the next candidate it' fairly easy to implementand not very temperamental sedgewick estimates it to be useful up to , items only when the shellsort proves too slow should you use one of the more complex but faster sortsmergesortheapsortor quicksort mergesort requires extra memoryheapsort requires heap data structureand both are somewhat slower than quicksortso quicksort is the usual choice when the fastest sorting time is necessary howeverquicksort is suspect if there' danger that the data may not be randomin which case it may deteriorate to ( performance for potentially non-random dataheapsort is better quicksort is also prone to subtle errors if it is not implemented correctly small mistakes in coding can make it work poorly for certain arrangements of dataa situation that may be hard to diagnose table comparison of sorting algorithms sort average worst bubble ( selection ( ( insertion ( ( shellsort ( / ( quicksort ( *logno( comparison extra memory ( poor no fair no good no / -no good no |
25,272 | ( *logno( *lognfair yes heapsort ( *logno( *lognfair no table summarizes the running time for various sorting algorithms the column labeled comparison attempts to estimate the minor speed differences between algorithms with the same average big times (there' no entry for shellsort because there are no other algorithms with the same big performance external storage in the previous discussion we assumed that data was stored in main memory howeveramounts of data too large to store in memory must be stored in external storagewhich generally means disk files we discussed external storage in the second parts of tables and external storage,and "hash tables we assumed that data is stored in disk file in fixed-size units called blockseach of which holds number of records ( record in disk file holds the same sort of data as an object in main memory like an objecta record has key value used to access it we also assumed that reading and writing operations always involve single blockand these read and write operations are far more time-consuming than any processing of data in main memory thus for fast operation the number of disk accesses must be minimized sequential storage the simplest approach is to store records randomly and read them sequentially when searching for one with particular key new records can simply be inserted at the end of the file deleted records can be marked as deletedor records can be shifted down (as in an arrayto fill in the gap on the averagesearching and deletion will involve reading half the blocksso sequential storage is not very fastoperating in (ntime stillit might be satisfactory for small number of records indexed files speed is increased dramatically when indexed files are used in this scheme an index of keys and corresponding block numbers is kept in main memory to access record with specified keythe index is consulted it supplies the block number for the keyand only one block needs to be readtaking ( time several indices with different kinds of keys can be used (one for last namesone for social security numbersand so onthis scheme works well until the index becomes too large to fit in memory typically the index files are themselves stored on disk and read into memory as needed the disadvantage of indexed files is that at some point the index must be created this probably involves reading through the file sequentiallyso creating the index is slow alsothe index will need to be updated when items are added to the file -trees |
25,273 | correspond to blocks on the disk as in other treesthe algorithms find their way down the treereading one block at each level -trees provide searchinginsertionand deletion of records in (logntime this is quite fast and works even for very large files howeverthe programming is not trivial hashing if it' acceptable to use about twice as much external storage as file would normally takethen external hashing might be good choice it has the same access time as indexed fileso( )but can handle larger files figure showsrather impressionisticallythese choices for external storage structures figure relationship of external storage choices virtual memory sometimes you can let your operating system' virtual memory capabilities (if it has themsolve disk access problems with little programming effort on your part if you read file that' too big to fit in main memorythe virtual memory system will read in that part of the file that fits and store the rest on the disk as you access different parts of the filethey will be read from the disk automatically and placed in memory you can apply internal algorithms to the entire file just as if it were all in memory at the same timeand let the operating system worry about reading the appropriate part of the file if it isn' in memory already of course operation will be much slower than when the entire file is in memorybut this would also be true if you dealt with the file block by block using one of the external-storage algorithms it may be worth simply ignoring the fact that file does not fit in memoryand see how well your algorithms work with the help of virtual memory especially for files that aren' much larger than the available memorythis may be an easy solution onward we've come to the end of our survey of data structures and algorithms the subject is large and complexso no one book can make you an expertbut we hope this book has made it easy for you to learn about the fundamentals appendix "further reading,contains suggestions for further study |
25,274 | appendix list appendix how to run the workshop applets and example aprograms appendix further reading bappendix ahow to run the workshop applets and example programs overview in this appendix we discuss the details of running the workshop applets and the example programs the workshop applets are graphics-based demonstration programs that show what trees and other data structures look like the example programswhose code is shown in the textpresent runnable java code the readme txt file in the cd-rom that accompanies this book contains further information on the topics discussed in this appendix be sure to read this file for the latest information on working with the workshop applets and example programs the java development kit both the workshop applets and the example programs can be executed using utility programs that are part of the sun microsystems java development kit (jdkthe jdk is included on the cd-rom the readme txt file on the cd-rom explains how appendix how to run the workshop applets and example programsto load the contents of the cd-rom onto your hard drive in this appendix we'll assume that you've transferred all appropriate filesincluding the jdk the cd-rom contains software to support various hardware and software platforms see the readme txt file for details we'll base this discussion on using the jdk in microsoft windows the details of usage in other platforms may vary command-line programs the jdk operates in text modeusing the command line to launch its various programs in windows you'll need to open an ms-dos box to obtain this command line click the start buttonand select ms-dos prompt from the programs menu thenin ms-dosuse the cd command to move to the appropriate subdirectory on your hard diskwhere either workshop applet or an example program is stored then execute the applet or program using the appropriate jdk utility as detailed below setting the path in windows the location of the jdk utility programs should be specified in path statement in the autoexec bat file so they can be accessed conveniently from within any subdirectory this path statement should be placed automatically in your autoexec bat file when you run the setup program on your cd-rom otherwiseuse the notepad utility to insert the line |
25,275 | "advancedstructureshoweverare characterized by their change of value and structure during the execution of program more sophisticated techniques are therefore needed for their implementation the sequence appears as hybrid in this classification it certainly varies its lengthbut that change in structure is of trivial nature since the sequence plays truly fundamental role in practically all computer systemsits treatment is included in chap the second treats sorting algorithms it displays variety of different methodsall serving the same purpose mathematical analysis of some of these algorithms shows the advantages and disadvantages of the methodsand it makes the programmer aware of the importance of analysis in the choice of good solutions for given problem the partitioning into methods for sorting arrays and methods for sorting files (often called internal and external sortingexhibits the crucial influence of data representation on the choice of applicable algorithms and on their complexity the space allocated to sorting would not be so large were it not for the fact that sorting constitutes an ideal vehicle for illustrating so many principles of programming and situations occurring in most other applications it often seems that one could compose an entire programming course by choosing examples from sorting only another topic that is usually omitted in introductory programming courses but one that plays an important role in the conception of many algorithmic solutions is recursion thereforethe third is devoted to recursive algorithms recursion is shown to be generalization of repetition (iteration)and as such it is an important and powerful concept in programming in many programming tutorialsit is unfortunately exemplified by cases in which simple iteration would suffice insteadchap concentrates on several examples of problems in which recursion allows for most natural formulation of solutionwhereas use of iteration would lead to obscure and cumbersome programs the class of backtracking algorithms emerges as an ideal application of recursionbut the most obvious candidates for the use of recursion are algorithms operating on data whose structure is defined recursively these cases are treated in the last two for which the third provides welcome background deals with dynamic data structuresi with data that change their structure during the execution of the program it is shown that the recursive data structures are an important subclass of the dynamic structures commonly used although recursive definition is both natural and possible in these casesit is usually not used in practice insteadthe mechanism used in its implementation is made evident to the programmer by forcing him to use explicit reference or pointer variables this book follows this technique and reflects the present state of the art is devoted to programming with pointersto liststrees and to examples involving even more complicated meshes of data it presents what is often (and somewhat inappropriatelycalled list processing fair amount of space is devoted to tree organizationsand in particular to search trees the ends with presentation of scatter tablesalso called "hashcodeswhich are often preferred to search trees this provides the possibility of comparing two fundamentally different techniques for frequently encountered application programming is constructive activity how can constructiveinventive activity be taughtone method is to crystallize elementary composition priciples out many cases and exhibit them in systematic manner but programming is field of vast variety often involving complex intellectual activities the belief that it could ever be condensed into sort of pure recipe teaching is mistaken what remains in our arsenal of teaching methods is the careful selection and presentation of master examples naturallywe should not believe that every person is capable of gaining equally much from the study of examples it is the characteristic of this approach that much is left to the studentto his diligence and intuition this is particularly true of the relatively involved and long example programs their inclusion in this book is not accidental longer programs are the prevalent case in practiceand they are much more suitable for exhibiting that elusive but essential ingredient called style and orderly structure they are also meant to serve as exercises in the art of program readingwhich too often is neglected in favor of program writing this is primary motivation behind the inclusion of larger programs as examples in their entirety the |
25,276 | reader is led through gradual development of the programhe is given various snapshots in the evolution of programwhereby this development becomes manifest as stepwise refinement of the details consider it essential that programs are shown in final form with sufficient attention to detailsfor in programmingthe devil hides in the details although the mere presentation of an algorithm' principle and its mathematical analysis may be stimulating and challenging to the academic mindit seems dishonest to the engineering practitioner have therefore strictly adhered to the rule of presenting the final programs in language in which they can actually be run on computer of coursethis raises the problem of finding form which at the same time is both machine executable and sufficiently machine independent to be included in such text in this respectneither widely used languages nor abstract notations proved to be adequate the language pascal provides an appropriate compromiseit had been developed with exactly this aim in mindand it is therefore used throughout this book the programs can easily be understood by programmers who are familiar with some other high-level languagesuch as algol or pl/ because it is easy to understand the pascal notation while proceeding through the text howeverthis not to say that some proparation would not be beneficial the book systematic programming [ provides an ideal background because it is also based on the pascal notation the present book washowevernot intended as manual on the language pascalthere exist more appropriate texts for this purpose [ this book is condensation and at the same time an elaboration of several courses on programming taught at the federal institute of technology (ethat zurich owe many ideas and views expressed in this book to discussions with my collaborators at eth in particulari wish to thank mr sandmayr for his careful reading of the manuscriptand miss heidi theiler and my wife for their care and patience in typing the text should also like to mention the stimulating influence provided by meetings of the working groups and of ifipand particularly the many memorable arguments had on these occasions with dijkstra and hoare last but not leasteth generously provided the environment and the computing facilities without which the preparation of this text would have been impossible zurichaug wirth [ dijkstraino - dahle dijkstrac hoare structured programming genuysed new yorkacademic press pp - [ hoare comm acm no ( ) - [ hoarein structured programming [ ]cc - [ wirth the programming language pascal acta informatica no ( ) - [ wirth program development by stepwise refinement comm acm no ( ) - [ wirth systematic programming englewood cliffsn prentice-hallinc [ jensen and wirth pascal-user manual and report berlinheidelbergnew yorkspringer-verlag |
25,277 | preface to the edition this new edition incorporates many revisions of details and several changes of more significant nature they were all motivated by experiences made in the ten years since the first edition appeared most of the contents and the style of the texthoweverhave been retained we briefly summarize the major alterations the major change which pervades the entire text concerns the programming language used to express the algorithms pascal has been replaced by modula- although this change is of no fundamental influence to the presentation of the algorithmsthe choice is justified by the simpler and more elegant syntactic structures of modula- which often lead to more lucid representation of an algorithm' structure apart from thisit appeared advisable to use notation that is rapidly gaining acceptance by wide communitybecause it is well-suited for the development of large programming systems neverthelessthe fact that pascal is modula' ancestor is very evident and eases the task of transition the syntax of modula is summarized in the appendix for easy reference as direct consequence of this change of programming languagesect on the sequential file structure has been rewritten modula- does not offer built-in file type the revised sect presents the concept of sequence as data structure in more general mannerand it introduces set of program modules that incorporate the sequence concept in modula- specifically the last part of is new it is dedicated to the subject of searching andstarting out with linear and binary searchleads to some recently invented fast string searching algorithms in this section in particular we use assertions and loop invariants to demonstrate the correctness of the presented algorithms new section on priority search trees rounds off the on dynamic data structures also this species of trees was unknown when the first edition appeared they allow an economical representation and fast search of point sets in plane the entire fifth of the first edition has been omitted it was felt that the subject of compiler construction was somewhat isolated from the preceding and would rather merit more extensive treatment in its own volume finallythe appearance of the new edition reflects development that has profoundly influenced publications in the last ten yearsthe use of computers and sophisticated algorithms to prepare and automatically typeset documents this book was edited and laid out by the author with the aid of lilith computer and its document editor lara without these toolsnot only would the book become more costlybut it would certainly not be finished yet palo altomarch wirth |
25,278 | notation the following notationsadopted from publications of dijkstraare used in this book in logical expressionsthe character denotes conjunction and is pronounced as and the character oboznachaet otritsanie chitaetsia kak denotes negation and is pronounced as not boldface and are used to denote the universal and existential quantifiers in the following formulasthe left part is the notation used and defined here in terms of the right part note that the left parts avoid the use of the symbol "which appeals to the readers intuition aim < pi pm pm+ pn- the pi are predicatesand the formula asserts that for all indices ranging from given value tobut excluding value pi holds eim < pi pm or pm+ or or pn- the pi are predicatesand the formula asserts that for some indices ranging from given value tobut excluding value pi holds sim < xi xm xm+ xn- min im < xi minimum(xm xn- max im < xi maximum(xm xn- |
25,279 | fundamental data structures introduction the modern digital computer was invented and intended as device that should facilitate and speed up complicated and time-consuming computations in the majority of applications its capability to store and access large amounts of information plays the dominant part and is considered to be its primary characteristicand its ability to computei to calculateto perform arithmetichas in many cases become almost irrelevant in all these casesthe large amount of information that is to be processed in some sense represents an abstraction of part of reality the information that is available to the computer consists of selected set of data about the actual problemnamely that set that is considered relevant to the problem at handthat set from which it is believed that the desired results can be derived the data represent an abstraction of reality in the sense that certain properties and characteristics of the real objects are ignored because they are peripheral and irrelevant to the particular problem an abstraction is thereby also simplification of facts we may regard personnel file of an employer as an example every employee is represented (abstractedon this file by set of data relevant either to the employer or to his accounting procedures this set may include some identification of the employeefor examplehis or her name and salary but it will most probably not include irrelevant data such as the hair colorweightand height in solving problem with or without computer it is necessary to choose an abstraction of realityi to define set of data that is to represent the real situation this choice must be guided by the problem to be solved then follows choice of representation of this information this choice is guided by the tool that is to solve the problemi by the facilities offered by the computer in most cases these two steps are not entirely separable the choice of representation of data is often fairly difficult oneand it is not uniquely determined by the facilities available it must always be taken in the light of the operations that are to be performed on the data good example is the representation of numberswhich are themselves abstractions of properties of objects to be characterized if addition is the only (or at least the dominantoperation to be performedthen good way to represent the number is to write strokes the addition rule on this representation is indeed very obvious and simple the roman numerals are based on the same principle of simplicityand the adding rules are similarly straightforward for small numbers on the other handthe representation by arabic numerals requires rules that are far from obvious (for small numbersand they must be memorized howeverthe situation is reversed when we consider either addition of large numbers or multiplication and division the decomposition of these operations into simpler ones is much easier in the case of representation by arabic numerals because of their systematic structuring principle that is based on positional weight of the digits it is generally known that computers use an internal representation based on binary digits (bitsthis representation is unsuitable for human beings because of the usually large number of digits involvedbut it is most suitable for electronic circuits because the two values and can be represented conveniently and reliably by the presence or absence of electric currentselectric chargeor magnetic fields from this example we can also see that the question of representation often transcends several levels of detail given the problem of representingsaythe position of an objectthe first decision may lead to the choice of pair of real numbers insayeither cartesian or polar coordinates the second decision may lead to floating-point representationwhere every real number consists of pair of integers denoting fraction and an exponent to certain base (such that ethe third decisionbased on the |
25,280 | knowledge that the data are to be stored in computermay lead to binarypositional representation of integersand the final decision could be to represent binary digits by the electric charge in semiconductor storage device evidentlythe first decision in this chain is mainly influenced by the problem situationand the later ones are progressively dependent on the tool and its technology thusit can hardly be required that programmer decide on the number representation to be employedor even on the storage device characteristics these lower-level decisions can be left to the designers of computer equipmentwho have the most information available on current technology with which to make sensible choice that will be acceptable for all (or almost allapplications where numbers play role in this contextthe significance of programming languages becomes apparent programming language represents an abstract computer capable of interpreting the terms used in this languagewhich may embody certain level of abstraction from the objects used by the actual machine thusthe programmer who uses such higher-level language will be freed (and barredfrom questions of number representationif the number is an elementary object in the realm of this language the importance of using language that offers convenient set of basic abstractions common to most problems of data processing lies mainly in the area of reliability of the resulting programs it is easier to design program based on reasoning with familiar notions of numberssetssequencesand repetitions than on bitsstorage unitsand jumps of coursean actual computer represents all datawhether numberssetsor sequencesas large mass of bits but this is irrelevant to the programmer as long as he or she does not have to worry about the details of representation of the chosen abstractionsand as long as he or she can rest assured that the corresponding representation chosen by the computer (or compileris reasonable for the stated purposes the closer the abstractions are to given computerthe easier it is to make representation choice for the engineer or implementor of the languageand the higher is the probability that single choice will be suitable for all (or almost allconceivable applications this fact sets definite limits on the degree of abstraction from given real computer for exampleit would not make sense to include geometric objects as basic data items in general-purpose languagesince their proper repesentation willbecause of its inherent complexitybe largely dependent on the operations to be applied to these objects the nature and frequency of these operations willhowevernot be known to the designer of general-purpose language and its compilerand any choice the designer makes may be inappropriate for some potential applications in this book these deliberations determine the choice of notation for the description of algorithms and their data clearlywe wish to use familiar notions of mathematicssuch as numberssetssequencesand so onrather than computer-dependent entities such as bitstrings but equally clearly we wish to use notation for which efficient compilers are known to exist it is equally unwise to use closely machineoriented and machine-dependent languageas it is unhelpful to describe computer programs in an abstract notation that leaves problems of representation widely open the programming language pascal had been designed in an attempt to find compromise between these extremesand the successor languages modula- and oberon are the result of decades of experience [ - oberon retains pascal' basic concepts and incorporates some improvements and some extensionsit is used throughout this book [ - it has been successfully implemented on several computersand it has been shown that the notation is sufficiently close to real machines that the chosen features and their representations can be clearly explained the language is also sufficiently close to other languagesand hence the lessons taught here may equally well be applied in their use the concept of data type in mathematics it is customary to classify variables according to certain important characteristics clear distinctions are made between realcomplexand logical variables or between variables representing individual valuesor sets of valuesor sets of setsor between functionsfunctionalssets of functionsand |
25,281 | so on this notion of classification is equally if not more important in data processing we will adhere to the principle that every constantvariableexpressionor function is of certain type this type essentially characterizes the set of values to which constant belongsor which can be assumed by variable or expressionor which can be generated by function in mathematical texts the type of variable is usually deducible from the typeface without consideration of contextthis is not feasible in computer programs usually there is one typeface available on computer equipment ( latin lettersthe rule is therefore widely accepted that the associated type is made explicit in declaration of the constantvariableor functionand that this declaration textually precedes the application of that constantvariableor function this rule is particularly sensible if one considers the fact that compiler has to make choice of representation of the object within the store of computer evidentlythe amount of storage allocated to variable will have to be chosen according to the size of the range of values that the variable may assume if this information is known to compilerso-called dynamic storage allocation can be avoided this is very often the key to an efficient realization of an algorithm the primary characteristics of the concept of type that is used throughout this textand that is embodied in the programming language oberonare the following [ - ]: data type determines the set of values to which constant belongsor which may be assumed by variable or an expressionor which may be generated by an operator or function the type of value denoted by constantvariableor expression may be derived from its form or its declaration without the necessity of executing the computational process each operator or function expects arguments of fixed type and yields result of fixed type if an operator admits arguments of several types ( is used for addition of both integers and real numbers)then the type of the result can be determined from specific language rules as consequencea compiler may use this information on types to check the legality of various constructs for examplethe mistaken assignment of boolean (logicalvalue to an arithmetic variable may be detected without executing the program this kind of redundancy in the program text is extremely useful as an aid in the development of programsand it must be considered as the primary advantage of good high-level languages over machine code (or symbolic assembly codeevidentlythe data will ultimately be represented by large number of binary digitsirrespective of whether or not the program had initially been conceived in high-level language using the concept of type or in typeless assembly code to the computerthe store is homogeneous mass of bits without apparent structure but it is exactly this abstract structure which alone is enabling human programmers to recognize meaning in the monotonous landscape of computer store the theory presented in this book and the programming language oberon specify certain methods of defining data types in most cases new data types are defined in terms of previously defined data types values of such type are usually conglomerates of component values of the previously defined constituent typesand they are said to be structured if there is only one constituent typethat isif all components are of the same constituent typethen it is known as the base type the number of distinct values belonging to type is called its cardinality the cardinality provides measure for the amount of storage needed to represent variable of the type denoted by xt since constituent types may again be structuredentire hierarchies of structures may be built upbutobviouslythe ultimate components of structure are atomic thereforeit is necessary that notation is provided to introduce such primitiveunstructured types as well straightforward method is that of enumerating the values that are to constitute the type for example in program concerned with plane geometric figureswe may introduce primitive type called shapewhose values may be denoted by the identifiers rectanglesquareellipsecircle but apart from such programmer-defined typesthere will |
25,282 | have to be some standardpredefined types they usually include numbers and logical values if an ordering exists among the individual valuesthen the type is said to be ordered or scalar in oberonall unstructured types are orderedin the case of explicit enumerationthe values are assumed to be ordered by their enumeration sequence with this tool in handit is possible to define primitive types and to build conglomeratesstructured types up to an arbitrary degree of nesting in practiceit is not sufficient to have only one general method of combining constituent types into structure with due regard to practical problems of representation and usea general-purpose programming language must offer several methods of structuring in mathematical sensethey are equivalentthey differ in the operators available to select components of these structures the basic structuring methods presented here are the arraythe recordthe setand the sequence more complicated structures are not usually defined as static typesbut are instead dynamically generated during the execution of the programwhen they may vary in size and shape such structures are the subject of chap and include listsringstreesand generalfinite graphs variables and data types are introduced in program in order to be used for computation to this enda set of operators must be available for each standard data type programming languages offers certain set of primitivestandard operatorsand likewise with each structuring method distinct operation and notation for selecting component the task of composition of operations is often considered the heart of the art of programming howeverit will become evident that the appropriate composition of data is equally fundamental and essential the most important basic operators are comparison and assignmenti the test for equality (and for order in the case of ordered types)and the command to enforce equality the fundamental difference between these two operations is emphasized by the clear distinction in their denotation throughout this text test for equalityx (an expression with value true or falseassignment to xx : ( statement making equal to ythese fundamental operators are defined for most data typesbut it should be noted that their execution may involve substantial amount of computational effortif the data are large and highly structured for the standard primitive data typeswe postulate not only the availability of assignment and comparisonbut also set of operators to create (computenew values thus we introduce the standard operations of arithmetic for numeric types and the elementary operators of propositional logic for logical values standard primitive types standard primitive types are those types that are available on most computers as built-in features they include the whole numbersthe logical truth valuesand set of printable characters on many computers fractional numbers are also incorporatedtogether with the standard arithmetic operations we denote these types by the identifiers integerrealbooleancharset the type integer the type integer comprises subset of the whole numbers whose size may vary among individual computer systems if computer uses its to represent an integer in two' complement notationthen the admissible values must satisfy - - < - it is assumed that all operations on data of this type are exact and correspond to the ordinary laws of arithmeticand that the computation will be interrupted in the case of result lying outside the representable subset this event is called overflow the standard operators are the four basic arithmetic operations of addition (+)subtraction ()multiplication (and |
25,283 | division (/divwhereas the slash denotes ordinary division resulting in value of type realthe operator div denotes integer division resulting in value of type integer if we define the quotient div and the remainder mod nthe following relations holdassuming * and < < examples div mod - div - - mod we know that dividing by can be achieved by merely shifting the decimal digits places to the right and thereby ignoring the lost digits the same method appliesif numbers are represented in binary instead of decimal form if two' complement representation is used (as in practically all modern computers)then the shifts implement division as defined by the above div operaton moderately sophisticated compilers will therefore represent an operation of the form div or mod by fast shift (or maskoperation the type real the type real denotes subset of the real numbers whereas arithmetic with operands of the types integer is assumed to yield exact resultsarithmetic on values of type real is permitted to be inaccurate within the limits of round-off errors caused by computation on finite number of digits this is the principal reason for the explicit distinction between the types integer and realas it is made in most programming languages the standard operators are the four basic arithmetic operations of addition (+)subtraction (-)multiplication (*)and division (/it is an essence of data typing that different types are incompatible under assignment an exception to this rule is made for assignment of integer values to real variablesbecause here the semanitcs are unambiguous after allintegers form subset of real numbers howeverthe inverse direction is not permissibleassignment of real value to an integer variable requires an operation such as truncation or rounding the standard transfer function entier(xyields the integral part of rounding of is obtained by entier( many programming languages do not include an exponentiation operator the following is an algorithm for the fast computation of xnwhere is non-negative integer : : (adens *( xi *while do if odd(ithen : * endx : *xi : div end |
25,284 | the type boolean the two values of the standard type boolean are denoted by the identifiers true and false the boolean operators are the logical conjunctiondisjunctionand negation whose values are defined in table the logical conjunction is denoted by the symbol &the logical disjunction by orand negation by "~note that comparisons are operations yielding result of type boolean thusthe result of comparison may be assigned to variableor it may be used as an operand of logical operator in boolean expression for instancegiven boolean variables and and integer variables the two assignments : :( < ( zyield false and true or & ~ true true true true false true false true false false false true true false true false false false false true table boolean operators the boolean operators (andand or have an additional property in most programming languageswhich distinguishes them from other dyadic operators whereasfor examplethe sum + is not definedif either or is undefinedthe conjunction & is defined even if is undefinedprovided that is false this conditionality is an important and useful property the exact definition of and or is therefore given by the following equationsp& if then else false or if then true else the type char the standard type char comprises set of printable characters unfortunatelythere is no generally accepted standard character set used on all computer systems thereforethe use of the predicate "standardmay in this case be almost misleadingit is to be understood in the sense of "standard on the computer system on which certain program is to be executed the character set defined by the international standards organization (iso)and particularly its american version ascii (american standard code for information interchangeis the most widely accepted set the ascii set is therefore tabulated in appendix it consists of printable (graphiccharacters and control charactersthe latter mainly being used in data transmission and for the control of printing equipment in order to be able to design algorithms involving characters ( values of type char)that are system independentwe should like to be able to assume certain minimal properties of character setsnamely the type char contains the capital latin lettersthe lower-case lettersthe decimal digitsand number of other graphic characterssuch as punctuation marks the subsets of letters and digits are ordered and contiguousi |
25,285 | (" < ( <" "implies that is capital letter (" < ( <" "implies that is lower-case letter (" < ( <" "implies that is decimal digit the type char contains non-printingblank character and line-end character that may be used as separators this is text fig representations of text the availability of two standard type transfer functions between the types char and integer is particularly important in the quest to write programs in machine independent form we will call them ord(ch)denoting the ordinal number of ch in the character setand chr( )denoting the character with ordinal number thuschr is the inverse function of ordand vice versathat isord(chr( ) (if chr(iis definedchr(ord( ) furthermorewe postulate standard function cap(chits value is defined as the capital letter corresponding to chprovided ch is letter ch is lower-case letter implies that cap(chcorresponding capital letter ch is capital letter implies that cap(chch the type set the type set denotes sets whose elements are integers in the range to small numbertypically or givenfor examplevariables var rstset possible assignments are :{ } :{xy } :{herethe value assigned to is the singleton set consisting of the single element to is assigned the empty setand to the elements xyy+ - the following elementary operators are defined on variables of type setin set intersection set union set difference symmetric set difference set membership constructing the intersection or the union of two sets is often called set multiplication or set additionrespectivelythe priorities of the set operators are defined accordinglywith the intersection operator having priority over the union and difference operatorswhich in turn have priority over the membership |
25,286 | operatorwhich is classified as relational operator following are examples of set expressions and their fully parenthesized equivalentsr + ( *st rst ( *tr + ( -st + ( /tx in in ( + the array structure the array is probably the most widely used data structurein some languages it is even the only one available an array consists of components which are all of the same typecalled its base typeit is therefore called homogeneous structure the array is random-access structurebecause all components can be selected at random and are equally quickly accessible in order to denote an individual componentthe name of the entire structure is augmented by the index selecting the component this index is to be an integer between and - where is the number of elementsthe sizeof the array type array of examples type row array of real type card array of char type name array of char particular value of variable var xrow with all components satisfying the equation xi -imay be visualized as shown in fig fig array of type row with xi - an individual component of an array can be selected by an index given an array variable xwe denote an array selector by the array name followed by the respective component' index iand we write xi or [ibecause of the firstconventional notationa component of an array component is therefore also called subscripted variable the common way of operating with arraysparticularly with large arraysis to selectively update single components rather than to construct entirely new structured values this is expressed by considering an array variable as an array of component variables and by permitting assignments to selected componentssuch as for example [ : although selective updating causes only single component value to changefrom conceptual point of view we must regard the entire composite value as having changed too the fact that array indicesi names of array componentsare integershas most important consequenceindices may be computed general index expression may be substituted in place of an index constantthis expression is to be evaluatedand the result identifies the selected component this |
25,287 | generality not only provides most significant and powerful programming facilitybut at the same time it also gives rise to one of the most frequently encountered programming mistakesthe resulting value may be outside the interval specified as the range of indices of the array we will assume that decent computing systems provide warning in the case of such mistaken access to non-existent array component the cardinality of structured typei the number of values belonging to this typeis the product of the cardinality of its components since all components of an array type are of the same base type we obtain card(tcard( ) constituents of array types may themselves be structured an array variable whose components are again arrays is called matrix for examplemarray of row is an array consisting of ten components (rows)each constisting of four components of type real and is called matrix with real components selectors may be concatenated accordinglysuch that mij and [ ][jdenote the -th component of row miwhich is the -th component of this is usually abbreviated as [ , ]and in the same spirit the declaration marray of array of real can be written more concisely as marray of real if certain operation has to be performed on all components of an array or on adjacent components of section of the arraythen this fact may conveniently be emphasized by using the for satementas shown in the following examples for computing the sum and for finding the maximal element of an array declared as var aarray of integer(adens *sum : for : to - do sum : [isum end : max : [ ]for : to - do if max [ithen :imax : [kend end in further exampleassume that fraction is represented in its decimal form with - digitsi by an array such that si < kdi - * * - *dk- now assume that we wish to divide by this is done by repeating the familiar division operation for all - digits distarting with = it consists of dividing each digit by taking into account possible carry from the previous positionand of retaining possible remainder for the next positionr : * + [ ] [ : div : mod this algorithm is used to compute table of negative powers of the repetition of halving to compute - - is again appropriately expressed by for statementthus leading to nesting of two for statements |
25,288 | procedure power (var wtexts writerninteger) (adens *(*compute decimal representation of negative powers of *var ikrintegerdarray of integerbegin for : to - do texts write( ") : for : to - do : * [ ] [ : div : mod texts write(wchr( [iord(" "))endd[ : texts write( " ")texts writeln(wend end power the resulting output text for is the record structure the most general method to obtain structured types is to join elements of arbitrary typesthat are possibly themselves structured typesinto compound examples from mathematics are complex numberscomposed of two real numbersand coordinates of pointscomposed of two or more numbers according to the dimensionality of the space spanned by the coordinate system an example from data processing is describing people by few relevant characteristicssuch as their first and last namestheir date of birthsexand marital status in mathematics such compound type is the cartesian product of its constituent types this stems from the fact that the set of values defined by this compound type consists of all possible combinations of valuestaken one from each set defined by each constituent type thusthe number of such combinationsalso called -tuplesis the product of the number of elements in each constituent setthat isthe cardinality of the compound type is the product of the cardinalities of the constituent types in data processingcomposite typessuch as descriptions of persons or objectsusually occur in files or data banks and record the relevant characteristics of person or object the word record has therefore become widely accepted to describe compound of data of this natureand we adopt this nomenclature in preference to the term cartesian product in generala record type with components of the types is defined as followstype record snt end card(tcard( card( card(tn |
25,289 | examples type complex record reimreal end type date record daymonthyearinteger end type person record namefirstnamenamebirthdatedatemaleboolean end we may visualize particularrecord-structured values offor examplethe variables zcomplex ddate pperson as shown in fig complex date person smith - john true fig records of type complexdate and person the identifiers sn introduced by record type definition are the names given to the individual components of variables of that type as components of records are called fieldsthe names are field identifiers they are used in record selectors applied to record structured variables given variable xt its -th field is denoted by si selective updating of is achieved by using the same selector denotation on the left side in an assignment statementx si : where is value (expressionof type givenfor examplethe record variables zdand declared abovethe following are selectors of componentsz im (of type reald month (of type integerp name (of type namep birthdate (of type datep birthdate day (of type integerp mail (of type booleanthe example of the type person shows that constituent of record type may itself be structured thusselectors may be concatenated naturallydifferent structuring types may also be used in nested fashion for examplethe -th component of an array being component of record variable is denoted by [ ]and the component with the selector name of the -th record structured component of the array is denoted by [is it is characteristic of the cartesian product that it contains all combinations of elements of the constituent types but it must be noted that in practical applications not all of them may be meaningful for instancethe type date as defined above includes the st april as well as the th february which are both dates that never occurred thusthe definition of this type does not mirror the actual situation |
25,290 | entirely correctlybut it is close enough for practical purposesand it is the responsibility of the programmer to ensure that meaningless values never occur during the execution of program the following short excerpt from program shows the use of record variables its purpose is to count the number of persons represented by the array variable family that are both female and born after the year var countintegerfamilyarray of personcount : for : to - do if ~family[imale (family[ibirthdate year then inc(countend end the record structure and the array structure have the common property that both are random-access structures the record is more general in the sense that there is no requirement that all constituent types must be identical in turnthe array offers greater flexibility by allowing its component selectors to be computable values (expressions)whereas the selectors of record components are field identifiers declared in the record type definition representation of arraysrecordsand sets the essence of the use of abstractions in programming is that program may be conceivedunderstoodand verified on the basis of the laws governing the abstractionsand that it is not necessary to have further insight and knowledge about the ways in which the abstractions are implemented and represented in particular computer neverthelessit is essential for professional programmer to have an understanding of widely used techniques for representing the basic concepts of programming abstractionssuch as the fundamental data structures it is helpful insofar as it might enable the programmer to make sensible decisions about program and data design in the light not only of the abstract properties of structuresbut also of their realizations on actual computerstaking into account computer' particular capabilities and limitations the problem of data representation is that of mapping the abstract structure onto computer store computer stores are -in first approximation -arrays of individual storage cells called bytes they are understood to be groups of bits the indices of the bytes are called addresses var storearray storesize of byte the basic types are represented by small number of bytestypically or computers are designed to transfer internally such small numbers (possibly of contiguous bytes concurrently"in parallelthe unit transferable concurrently is called word representation of arrays representation of an array structure is mapping of the (abstractarray with components of type onto the store which is an array with components of type byte the array should be mapped in such way that the computation of addresses of array components is as simple (and therefore as efficientas possible the address of the -th array component is computed by the linear mapping function *swhere is the address of the first componentand is the number of words that component occupies assuming that the word is the smallest individually transferable unit of storeit is evidently highly desirable that be whole numberthe simplest case being if is not whole number (and this is the normal |
25,291 | case)then is usually rounded up to the next larger integer each array component then occupies wordswhereby - words are left unused (see figs and rounding up of the number of words needed to the next whole number is called padding the storage utilization factor is the quotient of the minimal amounts of storage needed to represent structure and of the amount actually usedu ( rounded up to nearest integerstore array fig mapping an array onto store = = unused fig padded representation of record since an implementor has to aim for storage utilization as close to as possibleand since accessing parts of words is cumbersome and relatively inefficient processhe or she must compromise the following considerations are relevant padding decreases storage utilization omission of padding may necessitate inefficient partial word access partial word access may cause the code (compiled programto expand and therefore to counteract the gain obtained by omission of padding in factconsiderations and are usually so dominant that compilers always use padding automatically we notice that the utilization factor is always if howeverif < the utilization factor may be significantly increased by putting more than one array component into each word this technique is called packing if components are packed into wordthe utilization factor is (see fig * ( * rounded up to nearest integerpadded fig packing components into one word access to the -th component of packed array involves the computation of the word address in which the desired component is locatedand it involves the computation of the respective component position within the word div mod in most programming languages the programmer is given no control over the representation of the abstract |
25,292 | data structures howeverit should be possible to indicate the desirability of packing at least in those cases in which more than one component would fit into single wordi when gain of storage economy by factor of and more could be achieved we propose the convention to indicate the desirability of packing by prefixing the symbol array (or recordin the declaration by the symbol packed representation of records records are mapped onto computer store by simply juxtaposing their components the address of component (fieldri relative to the origin address of the record is called the field' offset ki it is computed as ki si- where sj is the size (in wordsof the -th component we now realize that the fact that all components of an array are of equal type has the welcome consequence that ki the generality of the record structure does unfortunately not allow such simplelinear function for offset address computationand it is therefore the very reason for the requirement that record components be selectable only by fixed identifiers this restriction has the desirable benefit that the respective offsets are known at compile time the resulting greater efficiency of record field access is well-known the technique of packing may be beneficialif several record components can be fitted into single storage word (see fig since offsets are computable by the compilerthe offset of field packed within word may also be determined by the compiler this means that on many computers packing of records causes deterioration in access efficiency considerably smaller than that caused by the packing of arrays padded fig representation of packed record representation of sets set is conveniently represented in computer store by its characteristic function (sthis is an array of logical values whose ith component has the meaning " is present in sas an examplethe set of small integers { is represented by the sequence of bitsby bitstringc( the representation of sets by their characteristic function has the advantage that the operations of computing the unionintersectionand difference of two sets may be implemented as elementary logical operations the following equivalenceswhich hold for all elements of the base type of the sets and yrelate logical operations with operations on setsi in ( + ( in xor ( in yi in ( * ( in ( in yi in ( - ( in ~( in |
25,293 | these logical operations are available on all digital computersand moreover they operate concurrently on all corresponding elements (bitsof word it therefore appears that in order to be able to implement the basic set operations in an efficient mannersets must be represented in smallfixed number of words upon which not only the basic logical operationsbut also those of shifting are available testing for membership is then implemented by single shift and subsequent (signbit test operation as consequencea test of the form in { ncan be implemented considerably more efficiently than the equivalent boolean expression ( or ( or or ( na corollary is that the set structure should be used only for small integers as elementsthe largest one being the wordlength of the underlying computer (minus the file or sequence another elementary structuring method is the sequence sequence is typically homogeneous structure like the array that isall its elements are of the same typethe base type of the sequence we shall denote sequence with elements by is called the length of the sequence this structure looks exactly like the array the essential difference is that in the case of the array the number of elements is fixed by the array' declarationwhereas for the sequence it is left open this implies that it may vary during execution of the program although every sequence has at any time specificfinite lengthwe must consider the cardinality of sequence type as infinitebecause there is no fixed limit to the potential length of sequence variables direct consequence of the variable length of sequences is the impossibility to allocate fixed amount of storage to sequence variables insteadstorage has to be allocated during program executionnamely whenever the sequence grows perhaps storage can be reclaimed when the sequence shrinks in any casea dynamic storage allocation scheme must be employed all structures with variable size share this propertywhich is so essential that we classify them as advanced structures in contrast to the fundamental structures discussed so far whatthencauses us to place the discussion of sequences in this on fundamental structuresthe primary reason is that the storage management strategy is sufficiently simple for sequences (in contrast to other advanced structures)if we enforce certain discipline in the use of sequences in factunder this proviso the handling of storage can safely be delegated to machanism that can be guaranteed to be reasonably effective the secondary reason is that sequences are indeed ubiquitous in all computer applications this structure is prevalent in all cases where different kinds of storage media are involvedi where data are to be moved from one medium to anothersuch as from disk or tape to primary store or vice-versa the discipline mentioned is the restraint to use sequential access only by this we mean that sequence is inspected by strictly proceeding from one element to its immediate successorand that it is generated by repeatedly appending an element at its end the immediate consequence is that elements are not directly accessiblewith the exception of the one element which currently is up for inspection it is this accessing discipline which fundamentally distinguishes sequences from arrays as we shall see in the influence of an access discipline on programs is profound the advantage of adhering to sequential access whichafter allis serious restrictionis the relative simplicity of needed storage management but even more important is the possibility to use effective buffering techniques when moving data to or from secondary storage devices sequential access allows us to feed streams of data through pipes between the different media buffering implies the collection of sections of stream in bufferand the subsequent shipment of the whole buffer content once the buffer is |
25,294 | filled this results in very significantly more effective use of secondary storage given sequential access onlythe buffering mechanism is reasonably straightforward for all sequences and all media it can therefore safely be built into system for general useand the programmer need not be burdened by incorporating it in the program such system is usually called file systembecause the high-volumesequential access devices are used for permanent storage of (persistentdataand they retain them even when the computer is switched off the unit of data on these media is commonly called (sequentialfile here we will use the term file as synonym to sequence there exist certain storage media in which the sequential access is indeed the only possible one among them are evidently all kinds of tapes but even on magnetic disks each recording track constitutes storage facility allowing only sequential access strictly sequential access is the primary characteristic of every mechanically moving device and of some other ones as well it follows that it is appropriate to distinguish between the data structurethe sequenceon one handand the mechanism to access elements on the other hand the former is declared as data structurethe latter typically by the introduction of record with associated operatorsoraccording to more modern terminologyby rider object the distinction between data and mechanism declarations is also useful in view of the fact that several access points may exist concurrently on one and the same sequenceeach one representing sequential access at (possiblydifferent location we summarize the essence of the foregoing as follows arrays and records are random access structures they are used when located in primaryrandomaccess store sequences are used to access data on secondarysequential-access storessuch as disks and tapes we distinguish between the declaration of sequence variableand that of an access mechanism located at certain position within the seqence elementary file operators the discipline of sequential access can be enforced by providing set of seqencing operators through which files can be accessed exclusively hencealthough we may here refer to the -th element of sequence by writing sithis shall not be possible in program sequencesfilesare typically largedynamic data structures stored on secondary storage device such device retains the data even if program is terminatedor computer is switched off therefore the introduction of file variable is complex operation connecting the data on the external device with the file variable in the program we therefore define the type file in separate modulewhose definition specifies the type together with its operators we call this module files and postulate that sequence or file variable must be explicitly initialized (openedby calling an appropriate operator or functionvar ffile :open(namewhere name identifies the file as recorded on the persistent data carrier some systems distinguish between opening an existing file and opening new filef :old(namef :new(namethe disconnection between secondary storage and the file variable then must also be explicitly requested byfor examplea call of close(fevidentlythe set of operators must contain an operator for generating (writingand one for inspecting (readinga sequence we postulate that these operations apply not to file directlybut to an object called riderwhich itself is connected with file (sequence)and which implements certain access mechanism the sequential access discipline is guaranteed by restrictive set of access operators (procedures |
25,295 | sequence is generated by appending elements at its end after having placed rider on the file assuming the declaration var rrider we position the rider on the file by the statement set(rfposwhere pos designates the beginning of the file (sequencea typical pattern for generating the sequence iswhile more do compute next element xwrite(rxend sequence is inspected by first positioning rider as shown aboveand then proceeding from element to element typical pattern for reading sequence isread(rx)while ~ eof do process element xread(rxend evidentlya certain position is always associated with every rider it is denoted by pos furthermorewe postulate that rider contain predicate (flagr eof indicating whether preceding read operation had reached the sequence' end we can now postulate and describe informally the following set of primitive operators new(fnamedefines to be the empty sequence old(fnamedefines to be the sequence persistently stored with given name set(rfposassociate rider with sequence fand place it at position pos write(rxplace element with value in the sequence designated by rider rand advance read(rxassign to the value of the element designated by rider rand advance close(fregisters the written file in the persistent store (flush buffersnote writing an element in sequence is often complex operation howevermostlyfiles are created by appending elements at the end translator' note primerakh programm knige ispol'zuiutsia eshche dve operatsii writeint(rnplace the integer in the sequence designated by rider rand advance readint(rnassign to the integer value designated by rider rand advance in order to convey more precise understanding of the sequencing operatorsthe following example of an implementation is provided it shows how they might be expressed if sequences were represented by arrays this example of an implementation intentionally builds upon concepts introduced and discussed earlierand it does not involve either buffering or sequential stores whichas mentioned abovemake the sequence concept truly necessary and attractive neverthelessthis example exhibits all the essential characteristics of the primitive sequence operatorsindependently of how the sequences are represented in store the operators are presented in terms of conventional procedures this collection of definitions of typesvariablesand procedure headings (signaturesis called definition we assume that we are to deal with sequences of charactersi text files whose elements are of type char the declarations of file and rider are good examples of an application of record structures becausein addition to the field denoting the array which represents the datafurther fields are required to denote the current length and positioni the state of the rider |
25,296 | definition files (adens _files *type file(*sequence of characters*rider record eofboolean endprocedure new(var namearray of char)fileprocedure old(var namearray of char)fileprocedure close(var ffile)procedure set(var rridervar ffileposinteger)procedure write(var rriderchchar)procedure read(var rridervar chchar)procedure writeint(var rriderninteger)procedure readint(var rridervar ninteger)end files definition represents an abstraction here we are given the two data typesfile and ridertogether with their operationsbut without further details revealing their actual representation in store of the operatorsdeclared as procedureswe see their headings only this hiding of the details of implementation is intentional the concept is called information hiding about riders we only learn that there is property called eof this flag is setif read operation reaches the end of the file the rider' position is invisibleand hence the rider' invariant cannot be falsified by direct access the invariant expresses the fact that the position always lies within the limits given by the associated sequence the invariant is established by procedure set and required and maintained by procedures read and write (also readint and writeintthe statements that implement the procedures and furtherinternal details of the data typesare sepecified in construct called module many representations of data and implementations of procedures are possible we chose the following as simple example (with fixed maximal file length)module files(adens _files *const maxlength type file pointer to record lenintegeraarray maxlength of char endrider record ( <pos < len <max length *ffileposintegereofboolean endprocedure new (namearray of char)filevar ffilebegin new( ) len : eof :false(*directory operation omitted*return end newprocedure old (namearray of char)filevar ffilebegin new( ) eof :false(*directory lookup omitted*return end oldprocedure close (var ffile)begin |
25,297 | end closeprocedure set (var rriderffileposinteger)begin (*assume nil* :fr eof :falseif pos > then if pos < len then pos :pos else pos : len end else pos : end end setprocedure write (var rriderchchar)begin if ( pos < len( pos maxlengththen [ pos:chinc( pos)if pos len then inc( lenend else eof :true end end writeprocedure read (var rridervar chchar)begin if pos len then ch : [ pos]inc( poselse eof :true end end readprocedure writeint (var rriderninteger)begin (*implementation is platform dependent*end writeintprocedure readint (var rridervar ninteger)begin (*implementation is platform dependent*end readintend files note that in this example the maximum length that sequences may reach is an arbitrary constant should program cause sequence to become longerthen this would not be mistake of the programbut an inadequacy of this implementation on the other handa read operation proceeding beyond the current end of the sequence would indeed be the program' mistake herethe flag eof is also used by the write operation to indicate that it was not possible to perform it hence~ eof is precondition for both read and write buffering sequences when data are transferred to or from secondary storage devicethe individual bits are transferred as stream usuallya device imposes strict timing constraints upon the transmission for exampleif data are written on tapethe tape moves at fixed speed and requires the data to be fed at fixed rate when the source ceasesthe tape movement is switched off and speed decreases quicklybut not instantaneously thus gap is left between the data transmitted and the data to follow at later time in order to achieve high density of datathe number of gaps ought to be kept smalland therefore data are transmitted in |
25,298 | relatively large blocks once the tape is moving similar conditions hold for magnetic diskswhere the data are allocated on tracks with fixed number of blocks of fixed sizethe so-called block size in facta disk should be regarded as an array of blockseach block being read or written as wholecontaining typically bytes with our programshoweverdo not observe any such timing constraints in order to allow them to ignore the constraintsthe data to be transferred are buffered they are collected in buffer variable (in main storeand transferred when sufficient amount of data is accumulated to form block of the required size the buffer' client has access only via the two procedures deposit and fetch definition bufferprocedure deposit (xchar)procedure fetch (var xchar)end buffer buffering has an additional advantage in allowing the process which generates (receivesdata to proceed concurrently with the device that writes (readsthe data from (tothe buffer in factit is convenient to regard the device as process itself which merely copies data streams the buffer' purpose is to provide certain degree of decoupling between the two processeswhich we shall call the producer and the consumer iffor examplethe consumer is slow at certain momentit may catch up with the producer later on this decoupling is often essential for good utilization of peripheral devicesbut it has only an effectif the rates of producer and consumer are about the same on the averagebut fluctuate at times the degree of decoupling grows with increasing buffer size we now turn to the question of how to represent bufferand shall for the time being assume that data elements are deposited and fetched individually instead of in blocks buffer essentially constitutes firstin-first-out queue (fifoif it is declared as an arraytwo index variablessay in and outmark the positions of the next location to be written into and to be read from ideallysuch an array should have no index bounds finite array is quite adequatehoweverconsidering the fact that elements once fetched are no longer relevant their location may well be re-used this leads to the idea of the circular buffer in out fig circular buffer with indices in and out the operations of depositing and fetching an element are expressed in the following modulewhich exports these operations as proceduresbut hides the buffer and its index variables -and thereby effectively the buffering mechanism -from the client processes this mechanism also involves variable counting the number of elements currently in the buffer if denotes the size of the bufferthe condition ((buffer non-empty)and the operation deposit by the condition (buffer non-fullnot meeting the former condition must be regarded as programming errora violation of the latter as failure of the suggested implementation (buffer too small |
25,299 | module buffer(*implements circular buffers*const (*buffer size*var ninoutintegerbufarray of charprocedure deposit (xchar)begin if then halt endinc( )buf[in:xin :(in mod end depositprocedure fetch (var xchar)begin if then halt enddec( ) :buf[out]out :(out mod end fetchbegin : in : out : end buffer this simple implementation of buffer is acceptable onlyif the procedures deposit and fetch are activated by single agent (once acting as produceronce as consumerifhoweverthey are activated by individualconcurrent processesthis scheme is too simplistic the reason is that the attempt to deposit into full bufferor the attempt to fetch from an empty bufferare quite legitimate the execution of these actions will merely have to be delayed until the guarding conditions are established such delays essentially constitute the necessary synchronization among concurrent processes we may represent these delays respectively by the statements repeat until repeat until which must be substituted for the two conditioned halt statements buffering between concurrent processes the presented solution ishowevernot recommendedeven if it is known that the two processes are driven by two individual engines the reason is that the two processors necessarily access the same variable nand therefore the same store the idling processby constantly polling the value nand therefore the same store the idling processby constantly polling the value nhinders its partnerbecause at no time can the store be accessed by more than one process this kind of busy waiting must indeed be avoidedand we therefore postulate facility that makes the details of synchronization less explicitin fact hides them we shall call this facility signaland assume that it is available from utility module signals together with set of primitive operators on signals every signal is associated with guard (conditionps if process needs to be delayed until ps is established (by some other process)it mustbefore proceedingwait for the signal this is to be expressed by the statement wait(sifon the other handa process establishes psit thereupon signals this fact by the statement send(sif ps is the established precondition to every statement send( )then ps can be regarded as postcondition of wait(sdefinition signalstype signalprocedure wait (var ssignal)procedure send (var ssignal)procedure init (var ssignal)end signals |