Topological Sorting in C

Advanced
6 min read
Updated: Nov 2026
1 example

Ordering Dependencies

A topological order lists the vertices of a directed acyclic graph so every edge u -> v has u before v. Kahn's algorithm: compute each vertex's in-degree, queue the vertices with in-degree 0, and repeatedly remove one, decrementing the in-degree of its neighbors and queueing any that reach 0. If fewer than V vertices are output, the graph has a cycle.

Remember
queue all vertices with indegree 0
while queue not empty:
    u = dequeue(); output u
    for each edge u -> v: if --indegree[v] == 0: enqueue(v)
if output count < V: cycle

Cheat Sheet

Keep these facts handy while you work with Topological Sorting in C in C.

TopicDetail
InputDirected acyclic graph
QueueVertices with in-degree 0
TimeO(V + E)
Cycle testOutput count < V

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Shortest Path Basics in C.

Example 1 — Order six tasks

Edges: 5->2, 5->0, 4->0, 4->1, 2->3, 3->1.

C
#include <stdio.h>
#define V 6

static int topo(int adj[V][V], int out[V]) {
    int indeg[V] = {0}, q[V], head = 0, tail = 0, n = 0;
    for (int u = 0; u < V; u++)
        for (int v = 0; v < V; v++) indeg[v] += adj[u][v];
    for (int v = 0; v < V; v++) if (indeg[v] == 0) q[tail++] = v;

    while (head < tail) {
        int u = q[head++];
        out[n++] = u;
        for (int v = 0; v < V; v++)
            if (adj[u][v] && --indeg[v] == 0) q[tail++] = v;
    }
    return n;
}

int main(void) {
    int adj[V][V] = {{0}}, out[V];
    int edges[][2] = {{5, 2}, {5, 0}, {4, 0}, {4, 1}, {2, 3}, {3, 1}};
    for (int i = 0; i < 6; i++) adj[edges[i][0]][edges[i][1]] = 1;

    int n = topo(adj, out);
    printf("topological order:");
    for (int i = 0; i < n; i++) printf(" %d", out[i]);
    printf("\n");

    int cyc[V][V] = {{0}};
    cyc[0][1] = cyc[1][2] = cyc[2][1] = 1;
    n = topo(cyc, out);
    printf("cyclic graph: %d of %d vertices ordered -> %s\n", n, V, n < V ? "cycle detected" : "ok");
    return 0;
}

How It Works

  1. Vertices 4 and 5 start with in-degree 0 and are output first.
  2. Removing 5 frees 0 and 2; removing 2 frees 3; removing 3 frees 1.
  3. In the cyclic graph, edges 1->2 and 2->1 keep vertices 1 and 2 above in-degree 0 forever, so only the other four vertices are ordered (4 of 6) and the shortfall reveals the cycle.

Edge Cases & Pitfalls

Check these before relying on Topological Sorting in C in real programs.

ties

Many valid orders

A DAG usually has several topological orders; yours depends on tie-breaking.

cyc

Ignoring cycle detection

Always compare the output count with the vertex count.

Key Takeaways

  • Queue the in-degree 0 vertices.
  • Decrement neighbors.
  • Count to detect cycles.

One line: A topological order lists the vertices of a directed acyclic graph so every edge u -> v has u before v.

Frequently Asked Questions

Scheduling tasks with dependencies, build systems, course prerequisites, and resolving dependency order.
No. A valid topological order exists only for directed acyclic graphs.
Continue with "Shortest Path Basics in C" next. Find shortest hop paths with BFS and learn edge relaxation. The C Graph Algorithms hub lists every topic in order.

Next: Shortest Path Basics in C

Find shortest hop paths with BFS and learn edge relaxation.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful