
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Topological Sorting in a Graph using C++
In this article, we will learn what is topological sorting, how to use it to detect cycles in a directed graph, and how to implement it in C++.
What is Topological Sort?
Topological sorting is an operation used to detect cycle in a graph. In this operation we order the vertices in such a way that for every directed edge u -> v, vertex u comes before vertex v in the ordering. If we are able to perform a topological sort in a graph, it means that the graph is a directed acyclic graph (DAG). The image below show how a topological sort is performed on a DAG.

The topological sorting order should start from the vertex with no incoming edges and end at the vertex with no outgoing edges. In this case, the order of the vertices is 0 -> 4 -> 1 -> 2 -> 3.
Khan's Algorithm for Topological Sorting
Topological sorting can be performed using Kahn's Algorithm. This is a BFS-based algorithm that uses the concept of in-degree of vertices.
Kahn's Algorithm works by using loops to find vertices with no incoming edges, and remove them from the graph, and then update the incoming edges of the vertices connected from the removed edges. This process continues until all vertices have been ordered. Let's see how this algorithm works in detail.
Steps to Perform Topological Sorting in a Graph
Following is the step-by-step process to check whether a topological sorting can be performed in a directed graph using Kahn's Algorithm:
- Declare an array indegree to keep track of the in-degree of each vertex.
- Calculate the in-degree for all vertices by using the adjacency list of the graph.
- Insert all vertices with in-degree 0 into a queue.
- Start running a while loop with condition that the queue is not empty.
- Inside the loop, remove a vertex from the front of the queue and store it in a variable U. Then, increase count variable. Then, for each neigr of U, decrease its in-degree by 1. If the in-degree of a neigr becomes 0, add it to the queue.
- After completion of the loop, if the count variable is equal to the number of vertices in the graph, then the topological sorting is successful.
Note: The in-degree of a vertex is the number of edges coming into that vertex.
C++ Program to Perform Topological Sorting
The code below implements above algorithm in C++ language. It creates a directed graph and checks whether a topological sorting can be performed on it.
#include <iostream> #include <vector> #include <queue> using namespace std; vector<int> isDAG(int V, vector<vector<int>>& adj) { vector<int> indegree(V, 0); vector<int> topologicalOrder; for (int u = 0; u < V; u++) { for (int v : adj[u]) { indegree[v]++; } } queue<int> q; for (int i = 0; i < V; i++) { if (indegree[i] == 0) q.push(i); } int count = 0; while (!q.empty()) { int node = q.front(); q.pop(); count++; topologicalOrder.push_back(node); for (int neigr : adj[node]) { indegree[neigr]--; if (indegree[neigr] == 0) q.push(neigr); } } return (count == V ? topologicalOrder : vector<int>()); } int main() { int V = 6; vector<vector<int>> adj(V); // Example Graph adj[5].push_back(2); adj[5].push_back(0); adj[4].push_back(0); adj[4].push_back(1); adj[2].push_back(3); adj[3].push_back(1); vector<int> result = isDAG(V, adj); if (!result.empty()) { cout << "Topological Sort Order: "; for (int node : result) { cout << node << " "; } cout << endl; } else { cout << "The graph contains a cycle. Topological sorting is not possible." << endl; } return 0; }
The output of the above code will be:
Topological Sort Order: 4 5 2 0 3 1
Time and Space Complexity
Time Complexity: The time complexity of this algorithm is O(n + m), where n is the number of vertices and m is the number of edges in the graph. This is because we are iterating through all vertices and edges to calculate the in-degrees and then processing each vertex once.
Space Complexity: The space complexity is O(n), where n is the number of vertices in the graph, as we are using an array to store the in-degrees and a queue for processing vertices.