Menu
Coddy logo textTech

Pseudo Code

Lesson 4 of 9 in Coddy's Topological Sort - Graph Algorithms course.

topologicalSort(n, edges):
   build directed adjacency; compute indeg[v] for all v
   order = []
   repeat n times:
      pick = smallest v with indeg[v] == 0 (none left -> stop)
      mark pick as used (indeg[pick] = -1)
      order.add(pick)
      for nb in adj[pick]:
         indeg[nb] -= 1
   return order
  • indeg[v] counts incoming edges. Only edges u -> v add to indeg[v].
  • Scanning vertices 0..n-1 and taking the first with in-degree 0 gives the smallest choice each step, so the order is deterministic.
  • Setting indeg[pick] = -1 is a simple way to mark a vertex as already placed.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Topological Sort - Graph Algorithms