Topological sort
The conceptHow a build tool knows which file to compile first
A topological sort puts tasks in an order where every task comes after everything it depends on. You draw each task as a dot and each 'needs' as an arrow from the needed task to the one that needs it. This is called a directed graph.
Take a small app. The app needs a parser and a network module, and both of those need a utils library. A valid order is utils, parser, network, app. Utils, network, parser, app works too: often there is more than one correct order.
What it’s forGives the running time of Kahn's algorithm, the standard way to compute a topological sort.
time = O(V + E)
- V
- the number of tasks (dots in the graph)
- E
- the number of 'needs' links (arrows)
- O(…)
- grows in proportion to, ignoring constant factors
What it givesThe work grows in step with the size of the dependency chart, so even huge projects sort quickly.
- The app example has 4 tasks and 4 arrows.
- Each task is queued once and each arrow is crossed once: 4 + 4 = 8 basic steps.
- With 1,000 tasks and 3,000 arrows: about 4,000 steps.