SlideShare a Scribd company logo
1 of 9
Topological Sort
• Introduction.
• Definition of Topological Sort.
• Topological Sort is Not Unique.
• Topological Sort Algorithm.
• An Example.
• Implementation.
• Review Questions.
Introduction
• There are many problems involving a set of tasks in
which some of the tasks must be done before others.
• For example, consider the problem of taking a course
only after taking its prerequisites.
• Is there any systematic way of linearly arranging the
courses in the order that they should be taken?
Yes! - Topological sort.
Definition of Topological Sort
• Topological sort is a method of arranging the vertices in a directed
acyclic graph (DAG), as a sequence, such that no vertex appear in
the sequence before its predecessor.
• The graph in (a) can be topologically sorted as in (b)
(a) (b)
Topological Sort is not unique
• Topological sort is not unique.
• The following are all topological sort of the graph below:
s1 = {a, b, c, d, e, f, g, h, i}
s2 = {a, c, b, f, e, d, h, g, i}
s3 = {a, b, d, c, e, g, f, h, i}
s4 = {a, c, f, b, e, h, d, g, i}
etc.
Topological Sort Algorithm
• One way to find a topological sort is to consider in-degrees of the vertices.
• The first vertex must have in-degree zero -- every DAG must have at least
one vertex with in-degree zero.
• The Topological sort algorithm is:
int topologicalOrderTraversal( ){
int numVisitedVertices = 0;
while(there are more vertices to be visited){
if(there is no vertex with in-degree 0)
break;
else{
select a vertex v that has in-degree 0;
visit v;
numVisitedVertices++;
delete v and all its emanating edges;
}
}
return numVisitedVertices;
}
Topological Sort Example
• Demonstrating Topological Sort.
A
F
B
G
C
H
D
I
E
J
1 2 3 0 2
1 0 2 2 0
D G A B F H J E I C
Implementation of Topological Sort
• The algorithm is implemented as a traversal method that visits the
vertices in a topological sort order.
• An array of length |V| is used to record the in-degrees of the
vertices. Hence no need to remove vertices or edges.
• A priority queue is used to keep track of vertices with in-degree zero
that are not yet visited.
public int topologicalOrderTraversal(Visitor visitor){
int numVerticesVisited = 0;
int[] inDegree = new int[numberOfVertices];
for(int i = 0; i < numberOfVertices; i++)
inDegree[i] = 0;
Iterator p = getEdges();
while (p.hasNext()) {
Edge edge = (Edge) p.next();
Vertex to = edge.getToVertex();
inDegree[getIndex(to)]++;
}
Implementation of Topological Sort
BinaryHeap queue = new BinaryHeap(numberOfVertices);
p = getVertices();
while(p.hasNext()){
Vertex v = (Vertex)p.next();
if(inDegree[getIndex(v)] == 0)
queue.enqueue(v);
}
while(!queue.isEmpty() && !visitor.isDone()){
Vertex v = (Vertex)queue.dequeueMin();
visitor.visit(v);
numVerticesVisited++;
p = v.getSuccessors();
while (p.hasNext()){
Vertex to = (Vertex) p.next();
if(--inDegree[getIndex(to)] == 0)
queue.enqueue(to);
}
}
return numVerticesVisited;
}
Review Questions
1. List the order in which the nodes of the directed graph GB are visited by
topological order traversal that starts from vertex a.
2. What kind of DAG has a unique topological sort?
3. Generate a directed graph using the required courses for your major. Now
apply topological sort on the directed graph you obtained.

More Related Content

Similar to Unit24_TopologicalSort (2).ppt

Topological Sort and Shortest Path in Directed Acyclic Graph with Single Source
Topological Sort and Shortest Path in Directed Acyclic Graph with Single SourceTopological Sort and Shortest Path in Directed Acyclic Graph with Single Source
Topological Sort and Shortest Path in Directed Acyclic Graph with Single SourceOğuzhan OSMA
 
Introduction to graphs
Introduction to graphsIntroduction to graphs
Introduction to graphsVenus Desiar
 
Unit VI - Graphs.ppt
Unit VI - Graphs.pptUnit VI - Graphs.ppt
Unit VI - Graphs.pptHODElex
 
Algorithms of graph
Algorithms of graphAlgorithms of graph
Algorithms of graphgetacew
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using javaNarayan Sau
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfArumugam90
 
Lecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdfLecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdfiftakhar8
 
Solid modeling
Solid modelingSolid modeling
Solid modelingKRvEsL
 
Topological Sorting (Decrease and Conquer)
Topological Sorting (Decrease and Conquer)Topological Sorting (Decrease and Conquer)
Topological Sorting (Decrease and Conquer)Gem WeBlog
 
Queue ADT for data structure for computer
Queue ADT for data structure for computerQueue ADT for data structure for computer
Queue ADT for data structure for computerabinathsabi
 
Lecture 9-online
Lecture 9-onlineLecture 9-online
Lecture 9-onlinelifebreath
 
Week2-stacks-queues.pptx
Week2-stacks-queues.pptxWeek2-stacks-queues.pptx
Week2-stacks-queues.pptxVandanaBharti21
 
Analysis of Pathfinding Algorithms
Analysis of Pathfinding AlgorithmsAnalysis of Pathfinding Algorithms
Analysis of Pathfinding AlgorithmsSigSegVSquad
 

Similar to Unit24_TopologicalSort (2).ppt (20)

Topological sorting
Topological sortingTopological sorting
Topological sorting
 
Topological Sort and Shortest Path in Directed Acyclic Graph with Single Source
Topological Sort and Shortest Path in Directed Acyclic Graph with Single SourceTopological Sort and Shortest Path in Directed Acyclic Graph with Single Source
Topological Sort and Shortest Path in Directed Acyclic Graph with Single Source
 
Introduction to graphs
Introduction to graphsIntroduction to graphs
Introduction to graphs
 
Graphs
GraphsGraphs
Graphs
 
Unit ix graph
Unit   ix    graph Unit   ix    graph
Unit ix graph
 
Unit VI - Graphs.ppt
Unit VI - Graphs.pptUnit VI - Graphs.ppt
Unit VI - Graphs.ppt
 
Algorithms of graph
Algorithms of graphAlgorithms of graph
Algorithms of graph
 
LEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdfLEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
 
Graph 1
Graph 1Graph 1
Graph 1
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using java
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdf
 
Lecture13
Lecture13Lecture13
Lecture13
 
Lecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdfLecture 16 - Dijkstra's Algorithm.pdf
Lecture 16 - Dijkstra's Algorithm.pdf
 
Solid modeling
Solid modelingSolid modeling
Solid modeling
 
6. Graphs
6. Graphs6. Graphs
6. Graphs
 
Topological Sorting (Decrease and Conquer)
Topological Sorting (Decrease and Conquer)Topological Sorting (Decrease and Conquer)
Topological Sorting (Decrease and Conquer)
 
Queue ADT for data structure for computer
Queue ADT for data structure for computerQueue ADT for data structure for computer
Queue ADT for data structure for computer
 
Lecture 9-online
Lecture 9-onlineLecture 9-online
Lecture 9-online
 
Week2-stacks-queues.pptx
Week2-stacks-queues.pptxWeek2-stacks-queues.pptx
Week2-stacks-queues.pptx
 
Analysis of Pathfinding Algorithms
Analysis of Pathfinding AlgorithmsAnalysis of Pathfinding Algorithms
Analysis of Pathfinding Algorithms
 

More from ShivareddyGangam

Student Voting Application for Election – Using SMS (1).pptx
Student Voting Application for Election – Using SMS (1).pptxStudent Voting Application for Election – Using SMS (1).pptx
Student Voting Application for Election – Using SMS (1).pptxShivareddyGangam
 
Project Management (2).pdf
Project Management (2).pdfProject Management (2).pdf
Project Management (2).pdfShivareddyGangam
 
The Product and Process(1).pdf
The Product and Process(1).pdfThe Product and Process(1).pdf
The Product and Process(1).pdfShivareddyGangam
 
artificialintelligencea-200326090832.pdf
artificialintelligencea-200326090832.pdfartificialintelligencea-200326090832.pdf
artificialintelligencea-200326090832.pdfShivareddyGangam
 
Software Project Risks Management (1).pdf
Software Project Risks Management (1).pdfSoftware Project Risks Management (1).pdf
Software Project Risks Management (1).pdfShivareddyGangam
 
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptx
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptxOS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptx
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptxShivareddyGangam
 
machinelearningengineeringslideshare-160909192132 (1).pdf
machinelearningengineeringslideshare-160909192132 (1).pdfmachinelearningengineeringslideshare-160909192132 (1).pdf
machinelearningengineeringslideshare-160909192132 (1).pdfShivareddyGangam
 
intelligent agent (1).pptx
intelligent agent (1).pptxintelligent agent (1).pptx
intelligent agent (1).pptxShivareddyGangam
 

More from ShivareddyGangam (20)

Student Voting Application for Election – Using SMS (1).pptx
Student Voting Application for Election – Using SMS (1).pptxStudent Voting Application for Election – Using SMS (1).pptx
Student Voting Application for Election – Using SMS (1).pptx
 
Project Management (2).pdf
Project Management (2).pdfProject Management (2).pdf
Project Management (2).pdf
 
pca.ppt
pca.pptpca.ppt
pca.ppt
 
The Product and Process(1).pdf
The Product and Process(1).pdfThe Product and Process(1).pdf
The Product and Process(1).pdf
 
Lecture1_jps (1).ppt
Lecture1_jps (1).pptLecture1_jps (1).ppt
Lecture1_jps (1).ppt
 
2 semai.pptx
2 semai.pptx2 semai.pptx
2 semai.pptx
 
artificialintelligencea-200326090832.pdf
artificialintelligencea-200326090832.pdfartificialintelligencea-200326090832.pdf
artificialintelligencea-200326090832.pdf
 
Software Project Risks Management (1).pdf
Software Project Risks Management (1).pdfSoftware Project Risks Management (1).pdf
Software Project Risks Management (1).pdf
 
Introduction (1).pdf
Introduction (1).pdfIntroduction (1).pdf
Introduction (1).pdf
 
Unit 3 (1) (1).pdf
Unit 3 (1) (1).pdfUnit 3 (1) (1).pdf
Unit 3 (1) (1).pdf
 
Unit 1 (1).pdf
Unit 1 (1).pdfUnit 1 (1).pdf
Unit 1 (1).pdf
 
Strassen.ppt
Strassen.pptStrassen.ppt
Strassen.ppt
 
Notion of Algorithms.pdf
Notion of Algorithms.pdfNotion of Algorithms.pdf
Notion of Algorithms.pdf
 
11_Automated_Testing.ppt
11_Automated_Testing.ppt11_Automated_Testing.ppt
11_Automated_Testing.ppt
 
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptx
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptxOS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptx
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptx
 
Project Management.pdf
Project Management.pdfProject Management.pdf
Project Management.pdf
 
PP
PPPP
PP
 
chapter2.ppt
chapter2.pptchapter2.ppt
chapter2.ppt
 
machinelearningengineeringslideshare-160909192132 (1).pdf
machinelearningengineeringslideshare-160909192132 (1).pdfmachinelearningengineeringslideshare-160909192132 (1).pdf
machinelearningengineeringslideshare-160909192132 (1).pdf
 
intelligent agent (1).pptx
intelligent agent (1).pptxintelligent agent (1).pptx
intelligent agent (1).pptx
 

Recently uploaded

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Recently uploaded (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 

Unit24_TopologicalSort (2).ppt

  • 1. Topological Sort • Introduction. • Definition of Topological Sort. • Topological Sort is Not Unique. • Topological Sort Algorithm. • An Example. • Implementation. • Review Questions.
  • 2. Introduction • There are many problems involving a set of tasks in which some of the tasks must be done before others. • For example, consider the problem of taking a course only after taking its prerequisites. • Is there any systematic way of linearly arranging the courses in the order that they should be taken? Yes! - Topological sort.
  • 3. Definition of Topological Sort • Topological sort is a method of arranging the vertices in a directed acyclic graph (DAG), as a sequence, such that no vertex appear in the sequence before its predecessor. • The graph in (a) can be topologically sorted as in (b) (a) (b)
  • 4. Topological Sort is not unique • Topological sort is not unique. • The following are all topological sort of the graph below: s1 = {a, b, c, d, e, f, g, h, i} s2 = {a, c, b, f, e, d, h, g, i} s3 = {a, b, d, c, e, g, f, h, i} s4 = {a, c, f, b, e, h, d, g, i} etc.
  • 5. Topological Sort Algorithm • One way to find a topological sort is to consider in-degrees of the vertices. • The first vertex must have in-degree zero -- every DAG must have at least one vertex with in-degree zero. • The Topological sort algorithm is: int topologicalOrderTraversal( ){ int numVisitedVertices = 0; while(there are more vertices to be visited){ if(there is no vertex with in-degree 0) break; else{ select a vertex v that has in-degree 0; visit v; numVisitedVertices++; delete v and all its emanating edges; } } return numVisitedVertices; }
  • 6. Topological Sort Example • Demonstrating Topological Sort. A F B G C H D I E J 1 2 3 0 2 1 0 2 2 0 D G A B F H J E I C
  • 7. Implementation of Topological Sort • The algorithm is implemented as a traversal method that visits the vertices in a topological sort order. • An array of length |V| is used to record the in-degrees of the vertices. Hence no need to remove vertices or edges. • A priority queue is used to keep track of vertices with in-degree zero that are not yet visited. public int topologicalOrderTraversal(Visitor visitor){ int numVerticesVisited = 0; int[] inDegree = new int[numberOfVertices]; for(int i = 0; i < numberOfVertices; i++) inDegree[i] = 0; Iterator p = getEdges(); while (p.hasNext()) { Edge edge = (Edge) p.next(); Vertex to = edge.getToVertex(); inDegree[getIndex(to)]++; }
  • 8. Implementation of Topological Sort BinaryHeap queue = new BinaryHeap(numberOfVertices); p = getVertices(); while(p.hasNext()){ Vertex v = (Vertex)p.next(); if(inDegree[getIndex(v)] == 0) queue.enqueue(v); } while(!queue.isEmpty() && !visitor.isDone()){ Vertex v = (Vertex)queue.dequeueMin(); visitor.visit(v); numVerticesVisited++; p = v.getSuccessors(); while (p.hasNext()){ Vertex to = (Vertex) p.next(); if(--inDegree[getIndex(to)] == 0) queue.enqueue(to); } } return numVerticesVisited; }
  • 9. Review Questions 1. List the order in which the nodes of the directed graph GB are visited by topological order traversal that starts from vertex a. 2. What kind of DAG has a unique topological sort? 3. Generate a directed graph using the required courses for your major. Now apply topological sort on the directed graph you obtained.