Sunday, May 4, 2014

Implementation of topological sorting in c++

topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge u->v from vertex u to vertex v, u comes before v in the ordering.

The canonical application of topological sorting  is in scheduling a sequence of jobs or tasks based on their dependencies;


#include<iostream.h>
int n,adj[100][100];
int front = -1,rear = -1,queue[100];
void main()
{
 int i,j = 0,k;
 int topsort[100],indeg[100];
 create_graph();
 cout<<"The adjacency matrix is:"<<"/n";
 display();
 for(i=1;i<+n;i++)
 {
  indeg[i]=indegree(i);
  if(indeg[i]==0)
   insert_queue(i);
 }
 while(front<=rear)
 {
  k=delete_queue();
  topsort[j++]=k;
  for(i=1;i<=n;i++)
  {
   if(adj[k][i]==1)
   {
    adj[k][i]=0;
    indeg[i]=indeg[i]-1;
    if(indeg[i]==0)
     insert_queue(i);
   }
  }
 }
 cout<<"Nodes after topological sorting are:\n");
 for(i=0;i<=n;i++)
  cout<<topsort[i];
 cout<<"\n";
}
create_graph()
{
 int i,max_edges,origin,destin;
 cout<<"\n Enter number of vertices:";
 scamf("%d",&n);
 max_edges = n * (n - 1);
 for(i = 1;i <= max_edges;i++)
 {
  cout<<"\n Enter edge "<<i<<" (00 to quit):";
  cin>>origin>>destin;
  if((origin == 0) && (destin == 0))
  {
   cout<<"Invalid edge!!\n";
   i–-;
  }
  else
   adj[origin][destin] = 1;
 }return;
}
display()
{
 int i,j;
 for(i = 0;i <= n;i++)
 {
  for(j = 1;jrear)
  {
   cout<<"Queue Underflow”;
   return;
  }
  else
  {
   del_item = queue[front];
   front = front + 1;
   return del_item;
  }
 }
 int indegree(int node)
 {
  int i,in_deg = 0;
  for(i = 1;i <= n;i++)
   if(adj[i][node] == 1)
    in_deg++;
  returnin_deg;
 }