topological sort of a directed graph
takes a list of pairs of node names
representing directed arcs in a graph and prints the nodes in topological
order on standard output. That is, the input describes a partial ordering
relation, from which tsort
computes a total order
compatible with this partial ordering.
Input is taken from the named file
, or from
standard input if no file is given.
Node names in the input are separated by white space and there must be an even
number of node names.
Presence of a node in a graph can be represented by an arc from the node to
itself. This is useful when a node is not connected to any other nodes.
If the graph contains a cycle (and therefore cannot be properly sorted), one of
the arcs in the cycle is ignored and the sort continues. Cycles are reported
on standard error.
The options are as follows:
- Resolve ambiguities by selecting nodes based on the order
of appearance of the first component of the pairs.
- Use file, which holds an
ordered list of nodes, to resolve ambiguities. In case of duplicates, the
first entry is chosen.
- Search for and display the longest cycle. Can take a very
long time, as it may need to solve an NP-complete problem.
- Do not display informational messages about cycles. This is
primarily intended for building libraries, where optimal ordering is not
critical, and cycles occur often.
- Reverse the ordering relation.
- Inform on the exact number of edges broken while breaking
cycles. If a hints file was used, inform on seen nodes absent from that
- Exit with exit code the number of cycles
tsort had to break.
utility exits 0 on success,
and >0 if an error occurs.
Faced with the input:
which is one total ordering compatible with the individual relations. There is
no unicity, another compatible total ordering would be:
is commonly used to analyze dependencies and
find a correct build order in a static way, whereas
accomplishes the same task
in a dynamic way.
Donald E. Knuth,
The Art of Computer Programming, Vol.
1, pp 258-268,
utility is compliant with the
IEEE Std 1003.1-2008
The flags [-fhlqrvw
extensions to that specification.
command appeared in
Version 7 AT&T UNIX
command was completely rewritten by Marc
Espie for OpenBSD
, to finally use the well-known
optimal algorithms for topological sorting.