Topological Sorting
Topological Sorting
Topological Sorting
Algorithms Data Structure Graph Algorithms
The topological sorting for a directed acyclic graph is the linear ordering of vertices. For
every edge U-V of a directed graph, the vertex u will come before vertex v in the
ordering.
As we know that the source vertex will come after the destination vertex, so we need to
use a stack to store previous elements. After completing all nodes, we can simply display
them from the stack.
Input:
000000
000000
000100
010000
110000
101000
Output:
Nodes after topological sorted order: 5 4 2 3 1 0
Algorithm
topoSort(u, visited, stack)
Page 2 of 4
Input − The start vertex u, An array to keep track of which node is visited or not. A
stack to store nodes.
Output − Sorting the vertices in topological sequence in the stack.
Begin
mark u as visited
for all vertices v which is adjacent with u, do
if v is not visited, then
topoSort(c, visited, stack)
done
performTopologicalSorting(Graph)
Begin
initially mark all nodes as unvisited
for all nodes v of the graph, do
if v is not visited, then
topoSort(i, visited, stack)
done
pop and print all elements from the stack
End.
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
Example
#include<iostream>
#include<stack>
#define NODE 6
using namespace std;
int graph[NODE][NODE] = {
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 0},
Page 3 of 4
{0, 1, 0, 0, 0, 0},
{1, 1, 0, 0, 0, 0},
{1, 0, 1, 0, 0, 0}
};
void performTopologicalSort() {
stack<int> stk;
bool vis[NODE];
while(!stk.empty()) {
cout << stk.top() << " ";
stk.pop();
}
}
main() {
cout << "Nodes after topological sorted order: ";
performTopologicalSort();
}
Output