
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
#define MAX 100
void topologicalSortKahn(int V, int edges[][2], int E) {
int indegree[MAX] = {0};
int adj[MAX][MAX] = {0};
int queue[MAX], front = 0, rear = 0;
int result[MAX], idx = 0;
for (int i = 0; i < E; i++) {
int u = edges[i][0];
int v = edges[i][1];
adj[u][v] = 1;
indegree[v]++;
}
for (int i = 0; i < V; i++) {
if (indegree[i] == 0)
queue[rear++] = i;
}
while (front < rear) {
int node = queue[front++];
result[idx++] = node;
for (int i = 0; i < V; i++) {
if (adj[node][i]) {
indegree[i]--;
if (indegree[i] == 0)
queue[rear++] = i;
}
}
}
if (idx != V) {
printf("Cycle detected\n");
return;
}
printf("Topological Sort: ");
for (int i = 0; i < idx; i++)
printf("%d ", result[i]);
printf("\n");
}
int main() {
int V = 6;
int edges[][2] = {{5, 2}, {5, 0}, {4, 0}, {4, 1}, {2, 3}, {3, 1}};
int E = sizeof(edges)/sizeof(edges[0]);
topologicalSortKahn(V, edges, E);
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(V + E) | Even in the best case, we must visit all vertices and all edges once to compute indegrees and process the graph structure. |
| Average Case | O(V + E) | For any valid DAG, each vertex and edge is processed exactly once. |
| Worst Case | O(V + E) | Regardless of graph structure (as long as it is a DAG), we always have to check every node and every edge at least once. |