Topological Sorting


Document last modified: 

Overview

Topological sorting is useful for defining the order things must be done. For example, prerequisites must be completed prior to certain course.

A DAG (directed acyclic graph) can model the problem (what is a cycle?) and the DFS can produce a sort that defines one valid ordering of paths to follow.

Question 22.16

 

Topological sort

Example

The following is a DAG at left that has been topologically sorted at right. It shows one valid ordering: DEABC.

Other valid orderings are possible from the DAG, for example: ADBEC

Question 22.17 - Which of the following are invalid orderings and why?

  1. ADEBC
  2. CBAED
  3. ABCDE
  4. DECAB

Example - Cormen page 613

A = {belt, jacket, pants, shirt, shoes, socks, tie, undershorts, watch}

R = {(a, b): a, b Î

a R b where once a has been put on, you won't have to take a off in order to put on b and if b is put on before a, then you would have to take b off in order to correctly put on a}

R = {(belt, jacket), (tie, jacket), (shirt, belt), (pants, belt), (pants, shoes), (shirt, tie), (undershorts, pants), (undershorts, shoes), (socks, shoes)}

Topological-Sort (G)
1 call DFS (G) to compute the v.f for each vertex v
2 as each vertex is finished, insert it onto the front of a linked list
3 return the linked list of vertices, which is sorted last to first finished

Start with shirt.

Question 22.18

  u v w x y z
p NIL u NIL y v w
d 1 1 9 4 3 10
f 8 7 12 5 6 11
DFS (G)
       -- Initialize arrays
1 for each vertex u Î G.V do
2    u.color ¬ WHITE
3    u.p ¬ NIL
4 time ¬ 0
5 for each vertex u Î G.V do
6     if u.color = WHITE then
7        DFS-Visit (G, u)
DFS-Visit (G, u)
1       u.color ¬ GRAY
2 time ¬ time + 1
3 u.d ¬ time
4 for each vertex v Î G.Adj[u] do
5    if v.color = WHITE then
6       v.p ¬ u
7       DFS-Visit (G, v)
8 u.color ¬ BLACK
9 u.f ¬ time ¬ time + 1

 

Ordering of Values in Sets