Professional Documents
Culture Documents
21MCA2205 (Topology Sort)
21MCA2205 (Topology Sort)
21MCA2205 (Topology Sort)
2. Task to be done: Write a program to demonstrate topological sort of n numbers with stacks.
3. Algorithm/Flowchart:
The topological sorting of a DAG is done in a order such that for every directed edge uv, vertex u comes
before v in the ordering. 5 has no incoming edge. 4 has no incoming edge, 2 and 0 have incoming edge
from 4 and 5 and 1 is placed at last.
#include <list>
#include <stack>
class Graph {
int V;
list<int>* adj
void topologicalSortUtil(int v, bool visited[],
stack<int>& Stack);
public:
Graph(int V);
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
topologicalSortUtil(*i, visited, Stack);
Stack.push(v);
}
void Graph::topologicalSort()
{
stack<int> Stack;
int main()
{
Graph g(6);
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
6. g.addEdge(3, 1);
7.
8. cout << "Following is a Topological Sort of the given "
9. "graph \n";
10. g.topologicalSort();
11.
12. return 0;
13. }
Evaluation Grid:
Sr. No. Parameters Marks Obtained Maximum Marks
1. Demonstration and Performance 5
2. Worksheet 10
3. Post Lab Quiz 5