AfterAcademy Tech
•
01 May 2020

In this blog, we will discuss Topological sort in a Directed Acyclic Graph i.e. DAG. We will discuss the following things:
Prerequisites
In the Directed Acyclic Graph, Topological sort is a way of the linear ordering of vertices v1, v2, …. vN in such a way that for every directed edge x → y, x will come before y in the ordering.
For example-The topological sort for the below graph is 1, 2, 4, 3, 5

Important Points to remember
Topological order can be one of the subsets of all the permutations of all the vertices following the condition that for every directed edge x → y, x will come before y in the ordering.
For that, we will maintain an array T[ ], which will store the ordering of the vertices in topological order. We will store the number of edges that are coming into a vertex in an array in_degree[N], where the i-th element will store the number of edges coming into the vertex i. We will also store whether a certain vertex has been visited or not in visited[N]. We will follow the belo steps:
in_degree is 0. That means there is no edge that is coming into that vertex.dequeue() the front element in the Queue and push it into the T.in_degree of the vertices which has an edge with the front vertex.in_degree is 0, we will push it in Queue and also mark that vertex as visited. (Hope you must be thinking its BFS but with in_degree)
topological_ordering(int N, bool adj[N][N])
{
int T[]
bool visited[N]
int in_degree[N]
for ( i = 0 to N-1 )
in_degree[i] = visited[i] = false
for ( i = 0 to N-1 )
for ( j = 0 to N-1 )
if (adj[i][j] == true)
in_degree[j] += 1
Q = Queue()
for ( i = 0 to N-1 )
{
if ( in_degree[i] == 0 ) {
Q.enqueue(i);
visited[i] = true
}
}
while( Q.size() != 0 )
{
curr = Q.front()
Q.dequeue();
T.append(curr);
for( j = 0 to N-1 )
{
if ( adj[curr][j] == true and visited[j] == false)
{
in_degree[j] -= 1
if (in_degree[j] == 0)
{
Q.enqueue(j)
visited[j] = true
}
}
}
}
return T
}
Happy Learning, Enjoy Algorithms!
Team AfterAcademy!
AfterAcademy Tech
Sort a linked list using Merge Sort. This is a very famous interview problem that demonstrates the concept of recursion. This problem is quite similar to Merge Sort in Arrays.

AfterAcademy Tech
Sorting is a famous problem solving approach during the interview. In this blog, we are going to discuss about the insertion and selection sort algorithm.

AfterAcademy Tech
Sort a linked list using insertion sort and return its head.

AfterAcademy Tech
In this blog, we will learn about various network topologies, their advantages and disadvantages in a computer network.
