You are on page 1of 6

Graphs Topological Sort

A.R. Hadaegh Dr. Ahmad R. Hadaegh

California State University San Marcos (CSUSM)

Page

Topological Sorting
When a set of tasks has to be performed, you may need to order the tasks based on priority or dependency For example, a student cannot take CSII unless he/she takes CSI First.

Or for example in a program, procedure 2 cannot be executed unless procedure 1 is executed; however, order of procedure 3 and procedure 4 may not be important A topological sort creates a linear structure of a diagram; that is it labels all its vertices with number 1, 2, , |V| so that i<j only if there is a path from vertex vi to vertex vj
A.R. Hadaegh Dr. Ahmad R. Hadaegh California State University San Marcos (CSUSM) Page 2

The diagram must not include cycle; otherwise, the topological sort is impossible The algorithm for topological sort is To find a vertex v with no outgoing edge called a sink or a minimal vertex and then disregard all edges leading from any vertex to v To summarize the above:
TopologicalSort (diagraph) for i=1 to |V| { find a minimal vertex v; num(v) = i; } remove from diagraph vertex v and all edges incident with v

The next example shows a graph that goes through a sequence of deletion to find the topological sort of the vertices
A.R. Hadaegh Dr. Ahmad R. Hadaegh California State University San Marcos (CSUSM) Page 3

a c f d

b e g

First minimal vertex is g c

a d f

b e

next one is e

a next one is f c next one is d a c


A.R. Hadaegh Dr. Ahmad R. Hadaegh

a
next one is b c f d c d

a d f

next one is c a

next one is a NULL


Page 4

California State University San Marcos (CSUSM)

TS(v) num(v) = i++; for all vertices u adjacent to v if num(u) = 0 TS(u) else if TSNum(u) = 0 // cycle is detected error; TSNum(v) =j++

This is a different algorithm that travels through the vertices and marks the vertices based on their dependency to find a topological sort of vertices This algorithm does not remove any vertex or edge from the graph

topologicalSorting(digraph) for all vertices v num(v) = TSNum(v) = 0 i = j = 1; while there is a vertex v such that num(v) = 0 TS(v) Output vertices according to their TSNums

A.R. Hadaegh Dr. Ahmad R. Hadaegh

California State University San Marcos (CSUSM)

Page

a c f d

b e g TSNum(c) = 6 c(2) TSNum(d) = 5 d(3) TSNum(b) = 3 b(4) TSNum(e) = 2 e(5) TSNum(g) = 1 g(6) e

a(1) TSNum(a) = 7 d f f(7) TSNum(f) = 4

The vertices are numbered as they are ordered

The topological sort of the vertices can be found if you print this tree in post order traversal gebfdca
A.R. Hadaegh Dr. Ahmad R. Hadaegh California State University San Marcos (CSUSM) Page 6

You might also like