首页 > 代码库 > Some facts about topological sort

Some facts about topological sort

Definition: a topological sort of a DAG G is a sort such that for all edge (i,j) in G, i precedes j.

Then we have following corollaries:

  • A sort is a topological sort of a DAG G iff for all i, j such that there is a path from i to j, i precedes j in the sort.
  • A sort is a topological sort of a DAG G iff for all i, j, if i precedes j, then there is no path from j to i.

A Lemma:

  • If in a DAG G, for i, j of G, there is not path from i to j and from j to i, then there must be a topological sort of G with i preceding j.

Proof:

Suppose there is a toplogical sort with j preceding i, then with the following procedure:

For every k between j and i, with the one nearest to j processed first:

   If there is a path from k to i, then move k right before j

Move i right before j

We can derive a topological order with i preceding j without breaking the validity of the order. The reason is that, since k is between j and i, then there is no path from k to j and no path from i to k. If there is a path from k to i, then there must be no path from j to k (because otherwise there would be a path from j to i). Then k can be moved before j without breaking the validity of the toplogical order. If there has been other vertices between j and i which are moved before j, then moving k right before j would keep the orginal preceding relationship between them. If there are other vertices before k that are not moved, for any such k‘, since there is no path from k‘ to i, then there is no path from k‘ to k (because otherwise there will be a path from k‘ to i), then k can also be moved in front of k‘ without breaking the validity of the toplogical sort. Since each step of the above procedure keeps the validity of the toplogical sort, we have derived a valid topological sort with this procedure.

Some facts about topological sort