logo
SEE ALGORITHMS
    Bubble Sort
    Insertion Sort
    Selection Sort
    Heap Sort
    Merge Sort
    Quick Sort
    Radix Sort

Topological Sorting

Topological Sorting is an ordering of nodes in a directed acyclic graph (DAG) where each node appears before all the nodes it points to. It is like creating a list of tasks, ensuring that each task comes after any tasks it depends on. The sorting can be achieved using Kahn's algorithm or DFS with a stack. Kahn's algorithm works by repeatedly removing nodes with no incoming edges (zero in-degree) and adding them to the order.

indeg = indegree()
stack = new Stack()
for each vertex v:
    if indeg[v] == 0: stack.push(v)
while stack is not empty:
    u = stack.pop()
    add u to sorted list
    for each neighbor v of u:
        indeg[v] = indeg[v] - 1
        if indeg[v] == 0: stack.push(v)
function indegree():
    indeg = map vertex -> 0
    for each vertex u:
        for each neighbor v of u:
            indeg[v] = indeg[v] + 1
    return indeg
Draw Graph

Curious to Learn More?

Hand-picked resources to deepen your understanding

Beginner Friendly
Grokking Algorithms

A friendly, fully illustrated guide. The best starting point for visual learners.

Practical Guide
A Common-Sense Guide to Data Structures and Algorithms

A practical guide with clear explanations and real-world examples.

Deep Dive
Introduction to Algorithms

The definitive guide (CLRS). Comprehensive and rigorous, perfect for deep diving into theory.

As an Amazon Associate, I earn from qualifying purchases. This helps support the site at no extra cost to you.

© 2025 SEE Algorithms. Code licensed under MIT, content under CC BY-NC 4.0.