Lecture 15 Topological Sort
Lecture 15 Topological Sort
Topological Sorting
Lecture #
Topological Sorting
• There are many problems involving a set of
tasks in which some of the tasks must be
done before others.
s2 = {a, c, b, f, e, d, h, g, i}
s3 = {a, b, d, c, e, g, f, h, i}
s4 = {a, c, f, b, e, h, d, g, i}
etc.
Topological Sort Algorithm
• One way to find a topological sort is to consider
in-degrees of the vertices.
• The first vertex must have in-degree zero -- every
DAG must have at least one vertex with in-
degree zero.
• The Topological sort algorithm is:
Algorithm
int topologicalOrderTraversal( ){
int numVisitedVertices = 0;
while(there are more vertices to be visited){
if(there is no vertex with in-degree 0)
break;
else{
select a vertex v that has in-degree 0;
visit v;(print v)
numVisitedVertices++;
delete v and all its emanating edges;
}
}
return numVisitedVertices;
}
Topological Sort Example
1 2 3 0 2
A B C D E
F G H I J
1 0 2 2 0
D G A B F H J E I C