notes66 - Topological Sort It is a sorting of the vertices...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Topological Sort It is a sorting of the vertices such that if there is an edge (i,j) then i should appear in the sorting before j Topological Sort: A,B,C,D,E,F or A,C,B,D,E,F Not a topological sort: C,E,A,B,D,F. (A doesn't appear before C) A topological sort is useful for scheduling of events that depend on each other. Example of using topological sort: A schedule of execution, such as for building a house Topological Sort 1. Foundation 2. Grass 3. Walls
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
4. Electric 5. Piping 6. Windows 7. End Algorithm: Topological Sorting Input: A diagraph G with n vertices Output: An array “sorted” with the vertices in topological order. // We use a stack to store the vertices with no dependencies stack{}; //Compute indegree of vertices for each edge(v,w){ // v->w indegree[w]++; } //Put vertices without incident edges (no dependencies) in stack for all u in G do if indegree[v] == 0 push v in stack; end end i=0; //index of "sorted" while stack is not empty u <- stack.pop() //u has no dependencies: add to "sorted" sorted[i] = u; i++; for all outgoing edges (u,w) of u do{ //remove dependency of u on w indegree[w]--; if indegree[w] == 0){ push w into stack; end end end if ( i < n ) { //not all vertices are sorted return null //topological sort not possible } return sorted Graphs with cycles do not have a topological sort! Class Graph{ int [] topoSort(){ //return an array with the vertices sorted topologically int [] indegree = new int[n]; //computer indegree for(int I = 0; I < n; i++){ for( int j = 0; j < n; j++){ if(adjacent[i][j]){ indegree[j]++; } } }
Background image of page 2
//initialize stack to keep track of vertices with indegree of 0 int[]
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/02/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University.

Page1 / 7

notes66 - Topological Sort It is a sorting of the vertices...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online