This preview shows pages 1–4. Sign up to view the full content.
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
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document 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]++;
}
}
}
//initialize stack to keep track of vertices with indegree of 0 int[]
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
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.
 Fall '08
 Staff
 Data Structures, Sort

Click to edit the document details