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 -> vadd toindeg[v]. - Scanning vertices
0..n-1and taking the first with in-degree 0 gives the smallest choice each step, so the order is deterministic. - Setting
indeg[pick] = -1is a simple way to mark a vertex as already placed.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Topological Sort - Graph Algorithms
2The Algorithm
How it works?Pseudo CodeImplementation (Part 1)Implementation (Part 2)