
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
int graph[MAX][MAX], indegree[MAX], queue[MAX];
int front = 0, rear = -1;
void enqueue(int v) { queue[++rear] = v; }
int dequeue() { return queue[front++]; }
void topologicalSort(int numTasks, int prerequisites[][2], int prereqSize) {
for (int i = 0; i < prereqSize; i++) {
int a = prerequisites[i][0];
int b = prerequisites[i][1];
graph[b][a] = 1;
indegree[a]++;
}
for (int i = 0; i < numTasks; i++)
if (indegree[i] == 0)
enqueue(i);
int count = 0;
while (front <= rear) {
int curr = dequeue();
printf("%d ", curr);
count++;
for (int i = 0; i < numTasks; i++) {
if (graph[curr][i] && --indegree[i] == 0)
enqueue(i);
}
}
if (count != numTasks)
printf("\nCycle detected. No valid ordering.\n");
}
int main() {
int prerequisites1[][2] = {{1,0},{2,0},{3,1},{3,2}};
topologicalSort(4, prerequisites1, 4);
printf("\n");
int prerequisites2[][2] = {{0,1},{1,0}};
topologicalSort(2, prerequisites2, 2);
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(V + E) | In the best case, we visit all vertices and edges once — one pass for building the graph and one pass for processing the queue. |
| Average Case | O(V + E) | Regardless of prerequisites distribution, all vertices and edges are still processed once each. |
| Worst Case | O(V + E) | Even with dense dependencies or cycles, we process each vertex and edge exactly once in topological sort. |