Title: Topological Sort
1Topological Sort
- Introduction.
- Definition of Topological Sort.
- Topological Sort is Not Unique.
- Topological Sort Algorithm.
- An Example.
- Implementation.
- Review Questions.
2Introduction
- There are many problems involving a set of tasks
in which some of the tasks must be done before
others. - For example, consider the problem of dressing up
for school in the morning. - Is there any systematic way of linearly arranging
the items in the order that they should be worn?
Yes! - Topological sort.
3Definition of Topological Sort
- Topological sort is a method of arranging the
vertices in a directed acyclic graph (DAG), as a
sequence, such that no vertex appear in the
sequence before its predecessor. - The graph in (a) can be topologically sorted as
in (b)
(a)
(b)
4Topological Sort is not unique
- Topological sort is not unique.
- The following are all topological sort of the
graph below
5Topological 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 full Algorithm goes as follows
1 Repeat the following until the graph is
empty 2 Select a vertex that has in-degree
zero. 3 Add the vertex to the sorted list. 4
Delete the vertex and all the edges emanating
from it.
6Topological Sort Example
- Demonstrating Topological Sort.
7Implementation of Topological Sort
- The algorithm is implemented as a traversal
method that visits the vertices in a topological
sort order. - An array of length V is used to record the
in-degrees of the vertices. Hence no need to
remove vertices or edges. - A queue is used to keep track of vertices with
in-degree zero that are not yet visited.
1 public void topologicalOrderTraversal(Visitor
visitor) 2 int inDegree new int
numberOfVertices 3 for (int v 0 v lt
numberOfVertices v) 4 inDegree v
0 5 Enumeration p getEdges () 6 while
(p.hasMoreElements ()) 7 Edge edge
(Edge) p.nextElement () 8 Vertex to
edge.getV1 () 9 inDegree to.getNumber
() 10
8Implementation of Topological Sort
- 11 Queue queue new QueueAsLinkedList ()
- 12 for (int v 0 v lt numberOfVertices v)
- 13 if (inDegree v 0)
- 14 queue.enqueue (vertex v)
- 15 while (!queue.isEmpty () !visitor.isDone
()) - 16 Vertex v (Vertex) queue.dequeue ()
- 17 visitor.visit (v)
- 18 Enumeration q v.getSuccessors ()
- 19 while (q.hasMoreElements ())
- 20 Vertex to (Vertex) q.nextElement
() - 21 if (--inDegree to.getNumber ()
0) - 22 queue.enqueue (to)
- 23
- 24
- 25
- 26 //
- 27
9Review Questions
1. List the order in which the nodes of the
directed graph GB are visited bya topological
order traversal that starts from vertex a. 2.
What kind of DAG has a unique topological
sort? 3. Generate a directed graph using the
required courses for your major. Now apply
topological sort on the directed graph you
obtained.