Kahn’s algorithm (1962) sorts a DAG in topological order by the following process:
- for every node, count how many predecessors feed into it (in-degree). Any node with a count of zero is ready
- pick any zero-count node and append it to the sorted output
- For each node that depends on the one just appended, subtract 1 from its in-degree; if that count reaches zero, the node becomes ready.
- loop until empty. If there is any node left, there is a cycle (the graph is not a DAG)
It’s time complexity is
Below is the pseudocode:
let sorted = []
let in_degrees = << number of incoming edge of each node >>
let queue = << all nodes with in-degree 0 >>
while queue is not empty:
n: node = queue.dequeue()
sorted.push_back(n)
for each node m with an edge e from n to m:
in_degrees[m] -= 1
if in_degrees[m] == 0:
queue.enqueue(m)
# If still have edges not processed, alternatively we can check whether the sorted list has the same size as the number of nodes
if in_degree is not all 0:
<< has cycle >>
else:
return sortedNote
the
queueabove can be replaced by another data structure, such as a stack or a priority queue. When more than one valid topological order exists, the choice of data structure can change which order is produced, but the result will always be correct