Topological Sort

1:The topological sort algorithm takes a directed graph and returns an array of the nodes where each node appears before all the nodes it points to.

The ordering of the nodes in the array is called a topological ordering.

The messy directed graph where node 1 points to nodes 2 and 3. Node 2 points to node 4 and 5, and node 4 points to node 5.
Since node 1 points to nodes 2 and 3, node 1 appears before them in the ordering. And, since nodes 2 and 3 both point to node 4, they appear before it in the ordering.
The topologically sorted directed graph where node 1 points to nodes 2 and 3. Node 2 points to node 4 and 5, and node 4 points to node 5.

Well, let’s focus on the first node in the topological ordering. That node can’t have any incoming directed edges; it must have an indegree ↴ of zero. Then follow below algorithm.

This is a common algorithm design pattern:

  1. Figure out how to get the first thing.
  2. Remove the first thing from the problem.
  3. Repeat.

Implementation

We’ll use the strategy we outlined above:

  1. Identify a node with no incoming edges.
  2. Add that node to the ordering.
  3. Remove it from the graph.
  4. Repeat.

Published by codeblogforfun

Coder, blogger, traveler

Leave a comment

Design a site like this with WordPress.com
Get started