Skip to main content

Topological Sorting

Definition​

Topological sorting is a linear ordering of vertices in a directed graph such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering

Practice​

topologicalSort(graph):
inDegree[] // array to store in-degree of vertices
queue // queue to store vertices with in-degree 0
topologicalOrder[] // list to store topological order

// Initialize in-degree array and queue
for each vertex v in graph:
inDegree[v] = 0
for each edge (u, v) in graph:
inDegree[v]++
if inDegree[v] == 0:
queue.enqueue(v)

// Perform topological sort
while queue is not empty:
u = queue.dequeue()
topologicalOrder.append(u)
for each neighbor v of u in graph:
inDegree[v]--
if inDegree[v] == 0:
queue.enqueue(v)

// Check for cycles
if size of topologicalOrder != number of vertices:
return "Graph has a cycle"

return topologicalOrder