Topological sorting is a linear ordering of the vertices in a directed acyclic graph (DAG) such that for every directed edge , vertex comes before vertex in the ordering. This concept is particularly useful in scenarios where there are dependencies between tasks, such as scheduling jobs, resolving symbol dependencies in linkers, or determining the order of course prerequisites in education.
There are two common methods for performing topological sorting:
Kahn’s Algorithm uses the concept of in-degree (the number of incoming edges for each vertex). Here’s how it works:
The DFS-based algorithm involves using depth-first traversal:
Here’s a C++ implementation using the DFS approach:
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Graph {
private:
int V; // Number of vertices
vector<vector<int>> adj; // Adjacency list
void topologicalSortUtil(int v, vector<bool>& visited, stack<int>& Stack) {
visited[v] = true; // Mark the current node as visited
// Recur for all the vertices adjacent to this vertex
for (int i : adj[v]) {
if (!visited[i]) {
topologicalSortUtil(i, visited, Stack);
}
}
// Push current vertex to stack which stores the result
Stack.push(v);
}
public:
Graph(int v) : V(v), adj(v) {}
void addEdge(int u, int v) {
adj[u].push_back(v); // Add edge from u to v
}
void topologicalSort() {
stack<int> Stack;
vector<bool> visited(V, false);
// Call the recursive helper function to store Topological Sort
for (int i = 0; i < V; i++) {
if (!visited[i]) {
topologicalSortUtil(i, visited, Stack);
}
}
// Print contents of stack
cout << "Topological Order: ";
while (!Stack.empty()) {
cout << Stack.top() << " ";
Stack.pop();
}
cout << endl;
}
};
int main() {
Graph g(6); // Create a graph with 6 vertices
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
g.topologicalSort(); // Perform topological sort
return 0;
}
Graph Class:
topologicalSortUtil Function:
topologicalSort Function:
Time Complexity:
Space Complexity:
Topological sorting is a fundamental algorithm for directed acyclic graphs that helps in ordering vertices based on dependencies. Understanding how to implement topological sorting, both through Kahn’s algorithm and depth-first search, is essential for solving problems related to scheduling and dependency resolution.
Open this section to load past papers