Graph Topological Sort — JavaScript implementation

I find this YouTube tutorial well explains topological sort, here I am going to implement the sample mentioned in the video by JavaScript.

Before we start the implementation, just to highlight again

Topological sorting only works for DAG (directed acyclic graph) : a directed graph with no directed cycles

Create sample graph

  • A must come before B and C
  • Both B and C must come before D
  • B and C are interchangeable since there is no edge between them
  • D must come before E

Helper function

This helper function will assign topological number to a given vertex.

Driver function

Finally, a driver function to trigger topological sorting.

Now each vertex is assigned with a number to form the topological sequence.