Topological Sort Code from Weis Data Structures...

indegree(V) = at any one time in algorithm, is the number of edges comming IN to the vertex V

Indegree of:

CS1020 = 0

CS1160 = 1

CS2360 = 1

CS2430 = 1

CS3240 = 2

After removing CS1020:

CS1160 = 0

CS2360 = 1

CS2430 = 1

CS3240 = 2

After removing CS1160:

CS2360 =0

CS2430 = 0

CS3240 = 2

After removing CS2360:

CS2430 = 0

CS3240 = 1

After removing CS2430:

CS3240 = 0

 

Pseudocode from Weiss Book

void Graph::topsort()
{
        Queue<Vertex> q;
        int counter =0;

        q.makeEmpty();

        for each Vertex v in G

           if( v.indegree == 0)
               q.enqueu(v);

       while(!q.isEmpty() )
       {
           
Vertex v = q.dequeue();
           v.topNum = ++counter;

           for each Vertex w adjacent to v
               if( --w.indegree == 0)
                   q.enqueue(w);
       }

      if(counter != num_vertices)
          throw CycleFoundException();

}

 

 

© Lynne Grewe