Implements a topological sort algorithm.
