SlideShare a Scribd company logo
Topological Sort Algorithm
Topological Sort
•It is a Linear ordering of its vertices such that for
every directed edge uv for Vertex u to v , u
comes before vertex v in the ordering.
•Graph Should be Directed Acyclic Graph (DAG)
•Every DAG will have atleast one Topological
Ordering
What is Directed Acyclic Graph(DAG)
• All rooted trees have a topological ordering since the do not contain
any cycle.
• Topological Ordering
• Picking from the bottom once root of subtree has create out children the
procedure continues so that we have no node’’
• In DFS, we print a vertex and then recursively call DFS for its adjacent
vertices. In topological sorting, we need to print a vertex before its
adjacent vertices.
Real Life Example
Some other applications of the topological sort are manufacturing workflows, project
management technique, context-free grammar
Course Schedule problem
There are some
courses and they may
have some
prerequisite courses.
One can finish
courses in some
order.
Prerequisites of course:
Algorithm of Topological Sort
In topological sorting,
•We use a temporary stack.
•We don’t print the vertex immediately,
•we first recursively call topological sorting for all its
adjacent vertices, then push it to a stack.
•Finally, print the contents of the stack.
Note:
A vertex is pushed to stack only when all of its adjacent vertices (and their
adjacent vertices and so on) are already in the stack
Algorithm of Topological Sort
1
3
0
B
2
5 4
0
1
2
3 1 /
/
3 /
1 /
0
/
4
5 0 /
2
0
• False
1
• False
3
• False
4
• False
5
• False
An adjacency list (based on In-degree)
An Empty Stack
Algorithm of Topological Sort
0 1
Step -1
0
0 1 3 2
0
1
2
3 1 /
/
3 /
1 /
0
/
4
5 0 /
2
Topological Sort (0) , Visited [0] = true
Adjacent List is Empty No More recursion CALL
Topological Sort (1) , Visited [1] = true
Adjacent List is Empty No More recursion call
Step -2
Step -3 Topological Sort (2) , Visited [2] = true
Topological Sort (3) , Visited [3] = true
“1” is already Visited No More recursion call
Algorithm of Topological Sort
0 1 3 2 4 5
Step -4
0 1 3 2 4
5 4 3 2 1 0
0
1
2
3 1 /
/
3 /
1 /
0
/
4
5 0 /
2
Topological Sort (4) , Visited [4] = true
“0” ,“1” are already Visited No More recursion call
Topological Sort (5) , Visited [5] = true
“2” ,“0” are already Visited No More
recursion call
Step -5
Step -3
Print all elements of stack from top to
bottom
Topological Sort of the given graph
Pseudocode of Topological Sort
topoSort(int u, bool visited[], stack<int>&stk) {
visited[u] = true; //set as the node v is visited
for(int v = 0; v<NODE; v++) {
if(graph[u][v]) { //for all vertices v adjacent to u
if(!visited[v])
topoSort(v, visited, stk);
}
}
stk.push(u); //push starting vertex into the stack
}
Computer Science Application
System Deadlock
Dependency resolution
Here B is the subclass of A and A is the subclass of B. This relationship is not possible. Java compiler
shows an error message
Complexities
• Time Complexity: O(V + E) where V = Vertices, E = Edges.
• To determine the in-degree of each node, we will have to iterate through all
the edges of the graph. So the time complexity of this step is O(E).
• Next, look for nodes with in-degrees equal to 0. This will require us to iterate
through the entire array that stores the in-degrees of each node. The size of
this array is equal to V. So, the time complexity of this step is O(V).
• Auxiliary space: O(V), We have to create one array to store the in-
degrees of all the nodes. This will require O(V) space.
Advantages
• Requires linear time and linear space to perform.
• Effective in detecting cyclic dependencies.
• Can efficiently find feedback loops that should not exist in a
combinational circuit.
• Can be used to find the shortest path between two nodes in
a DAG in linear time.
Disadvantages
Topological sort is not
possible for a graph that is
not directed and acyclic.
References
• https://www.interviewkickstart.com/learn/topological-
sort#:~:text=The%20time%20complexity%20of%20topological,the%2
0edges%20of%20the%20graph.
• https://www.geeksforgeeks.org/topological-sorting/
• https://iq.opengenus.org/applications-of-topological-sort/

More Related Content

What's hot

Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structureSajid Marwat
 
sum of subset problem using Backtracking
sum of subset problem using Backtrackingsum of subset problem using Backtracking
sum of subset problem using Backtracking
Abhishek Singh
 
Introduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of OptimalityIntroduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of Optimality
Bhavin Darji
 
DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems
Venkata Sreeram
 
A* Search Algorithm
A* Search AlgorithmA* Search Algorithm
A* Search Algorithm
vikas dhakane
 
Data link layer
Data link layer Data link layer
Data link layer
Mukesh Chinta
 
B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data StructureAnuj Modi
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithmMohd Arif
 
File system structure
File system structureFile system structure
File system structure
sangrampatil81
 
Randomized algorithms ver 1.0
Randomized algorithms ver 1.0Randomized algorithms ver 1.0
Randomized algorithms ver 1.0
Dr. C.V. Suresh Babu
 
data structures- back tracking
data structures- back trackingdata structures- back tracking
data structures- back tracking
Abinaya B
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
Dr Shashikant Athawale
 
The n Queen Problem
The n Queen ProblemThe n Queen Problem
The n Queen Problem
Sukrit Gupta
 
TCP and UDP
TCP and UDP TCP and UDP
TCP and UDP
Ramesh Giri
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
Gokul Hari
 
Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Tree
khabbab_h
 
Page replacement algorithms
Page replacement algorithmsPage replacement algorithms
Page replacement algorithmsPiyush Rochwani
 
Fault tolerance in distributed systems
Fault tolerance in distributed systemsFault tolerance in distributed systems
Fault tolerance in distributed systemssumitjain2013
 
Network security - OSI Security Architecture
Network security - OSI Security ArchitectureNetwork security - OSI Security Architecture
Network security - OSI Security Architecture
BharathiKrishna6
 

What's hot (20)

Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structure
 
sum of subset problem using Backtracking
sum of subset problem using Backtrackingsum of subset problem using Backtracking
sum of subset problem using Backtracking
 
Introduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of OptimalityIntroduction to Dynamic Programming, Principle of Optimality
Introduction to Dynamic Programming, Principle of Optimality
 
DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems
 
A* Search Algorithm
A* Search AlgorithmA* Search Algorithm
A* Search Algorithm
 
Data link layer
Data link layer Data link layer
Data link layer
 
B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
 
File system structure
File system structureFile system structure
File system structure
 
Randomized algorithms ver 1.0
Randomized algorithms ver 1.0Randomized algorithms ver 1.0
Randomized algorithms ver 1.0
 
data structures- back tracking
data structures- back trackingdata structures- back tracking
data structures- back tracking
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
The n Queen Problem
The n Queen ProblemThe n Queen Problem
The n Queen Problem
 
TCP and UDP
TCP and UDP TCP and UDP
TCP and UDP
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
Input output in linux
Input output in linuxInput output in linux
Input output in linux
 
Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Tree
 
Page replacement algorithms
Page replacement algorithmsPage replacement algorithms
Page replacement algorithms
 
Fault tolerance in distributed systems
Fault tolerance in distributed systemsFault tolerance in distributed systems
Fault tolerance in distributed systems
 
Network security - OSI Security Architecture
Network security - OSI Security ArchitectureNetwork security - OSI Security Architecture
Network security - OSI Security Architecture
 

Similar to Topological Sort Algorithm.pptx

Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1
Puja Koch
 
Unit24_TopologicalSort (2).ppt
Unit24_TopologicalSort (2).pptUnit24_TopologicalSort (2).ppt
Unit24_TopologicalSort (2).ppt
ShivareddyGangam
 
Lecture 11.2 : sorting
Lecture 11.2 :  sortingLecture 11.2 :  sorting
Lecture 11.2 : sorting
Vivek Bhargav
 
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
Oğuzhan OSMA
 
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIADheeraj Kataria
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
Afaq Mansoor Khan
 
Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdf
AkashSingh625550
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using java
Narayan Sau
 
Topological sort
Topological sortTopological sort
Topological sort
stella D
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdf
Arumugam90
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
Dr.Umadevi V
 
Halo2 Verifier in Move from ZERO to ONE.pptx
Halo2 Verifier in Move from ZERO to ONE.pptxHalo2 Verifier in Move from ZERO to ONE.pptx
Halo2 Verifier in Move from ZERO to ONE.pptx
funfriendcjf
 
Unit VI - Graphs.ppt
Unit VI - Graphs.pptUnit VI - Graphs.ppt
Unit VI - Graphs.ppt
HODElex
 
Data structures
Data structuresData structures
Data structures
Pranav Gupta
 
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2Yo Halb
 
quick sort by deepak.pptx
quick sort by deepak.pptxquick sort by deepak.pptx
quick sort by deepak.pptx
DeepakM509554
 
ADS_Lec2_Linked_Allocation
ADS_Lec2_Linked_AllocationADS_Lec2_Linked_Allocation
ADS_Lec2_Linked_Allocation
Hemanth Kumar
 

Similar to Topological Sort Algorithm.pptx (20)

Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1
 
Unit24_TopologicalSort (2).ppt
Unit24_TopologicalSort (2).pptUnit24_TopologicalSort (2).ppt
Unit24_TopologicalSort (2).ppt
 
Lecture 11.2 : sorting
Lecture 11.2 :  sortingLecture 11.2 :  sorting
Lecture 11.2 : 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
 
Data structure
Data structureData structure
Data structure
 
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 
Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdf
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using java
 
Topological sort
Topological sortTopological sort
Topological sort
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdf
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
Halo2 Verifier in Move from ZERO to ONE.pptx
Halo2 Verifier in Move from ZERO to ONE.pptxHalo2 Verifier in Move from ZERO to ONE.pptx
Halo2 Verifier in Move from ZERO to ONE.pptx
 
Discrete_4.pptx
Discrete_4.pptxDiscrete_4.pptx
Discrete_4.pptx
 
Unit VI - Graphs.ppt
Unit VI - Graphs.pptUnit VI - Graphs.ppt
Unit VI - Graphs.ppt
 
Data structures
Data structuresData structures
Data structures
 
Matlab lec1
Matlab lec1Matlab lec1
Matlab lec1
 
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
[YIDLUG] Programming Languages Differences, The Underlying Implementation 1 of 2
 
quick sort by deepak.pptx
quick sort by deepak.pptxquick sort by deepak.pptx
quick sort by deepak.pptx
 
ADS_Lec2_Linked_Allocation
ADS_Lec2_Linked_AllocationADS_Lec2_Linked_Allocation
ADS_Lec2_Linked_Allocation
 

Recently uploaded

In silico drugs analogue design: novobiocin analogues.pptx
In silico drugs analogue design: novobiocin analogues.pptxIn silico drugs analogue design: novobiocin analogues.pptx
In silico drugs analogue design: novobiocin analogues.pptx
AlaminAfendy1
 
ESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptxESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptx
muralinath2
 
Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
NathanBaughman3
 
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
muralinath2
 
Seminar of U.V. Spectroscopy by SAMIR PANDA
 Seminar of U.V. Spectroscopy by SAMIR PANDA Seminar of U.V. Spectroscopy by SAMIR PANDA
Seminar of U.V. Spectroscopy by SAMIR PANDA
SAMIR PANDA
 
RNA INTERFERENCE: UNRAVELING GENETIC SILENCING
RNA INTERFERENCE: UNRAVELING GENETIC SILENCINGRNA INTERFERENCE: UNRAVELING GENETIC SILENCING
RNA INTERFERENCE: UNRAVELING GENETIC SILENCING
AADYARAJPANDEY1
 
GBSN - Microbiology (Lab 4) Culture Media
GBSN - Microbiology (Lab 4) Culture MediaGBSN - Microbiology (Lab 4) Culture Media
GBSN - Microbiology (Lab 4) Culture Media
Areesha Ahmad
 
platelets- lifespan -Clot retraction-disorders.pptx
platelets- lifespan -Clot retraction-disorders.pptxplatelets- lifespan -Clot retraction-disorders.pptx
platelets- lifespan -Clot retraction-disorders.pptx
muralinath2
 
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
University of Maribor
 
Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...
Sérgio Sacani
 
Leaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdfLeaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdf
RenuJangid3
 
Hemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptxHemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptx
muralinath2
 
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of LipidsGBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
Areesha Ahmad
 
Orion Air Quality Monitoring Systems - CWS
Orion Air Quality Monitoring Systems - CWSOrion Air Quality Monitoring Systems - CWS
Orion Air Quality Monitoring Systems - CWS
Columbia Weather Systems
 
Cancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate PathwayCancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate Pathway
AADYARAJPANDEY1
 
Richard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlandsRichard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlands
Richard Gill
 
Comparative structure of adrenal gland in vertebrates
Comparative structure of adrenal gland in vertebratesComparative structure of adrenal gland in vertebrates
Comparative structure of adrenal gland in vertebrates
sachin783648
 
Richard's entangled aventures in wonderland
Richard's entangled aventures in wonderlandRichard's entangled aventures in wonderland
Richard's entangled aventures in wonderland
Richard Gill
 
erythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptxerythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptx
muralinath2
 
Lateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensiveLateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensive
silvermistyshot
 

Recently uploaded (20)

In silico drugs analogue design: novobiocin analogues.pptx
In silico drugs analogue design: novobiocin analogues.pptxIn silico drugs analogue design: novobiocin analogues.pptx
In silico drugs analogue design: novobiocin analogues.pptx
 
ESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptxESR_factors_affect-clinic significance-Pathysiology.pptx
ESR_factors_affect-clinic significance-Pathysiology.pptx
 
Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
Astronomy Update- Curiosity’s exploration of Mars _ Local Briefs _ leadertele...
 
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
Circulatory system_ Laplace law. Ohms law.reynaults law,baro-chemo-receptors-...
 
Seminar of U.V. Spectroscopy by SAMIR PANDA
 Seminar of U.V. Spectroscopy by SAMIR PANDA Seminar of U.V. Spectroscopy by SAMIR PANDA
Seminar of U.V. Spectroscopy by SAMIR PANDA
 
RNA INTERFERENCE: UNRAVELING GENETIC SILENCING
RNA INTERFERENCE: UNRAVELING GENETIC SILENCINGRNA INTERFERENCE: UNRAVELING GENETIC SILENCING
RNA INTERFERENCE: UNRAVELING GENETIC SILENCING
 
GBSN - Microbiology (Lab 4) Culture Media
GBSN - Microbiology (Lab 4) Culture MediaGBSN - Microbiology (Lab 4) Culture Media
GBSN - Microbiology (Lab 4) Culture Media
 
platelets- lifespan -Clot retraction-disorders.pptx
platelets- lifespan -Clot retraction-disorders.pptxplatelets- lifespan -Clot retraction-disorders.pptx
platelets- lifespan -Clot retraction-disorders.pptx
 
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
 
Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...Multi-source connectivity as the driver of solar wind variability in the heli...
Multi-source connectivity as the driver of solar wind variability in the heli...
 
Leaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdfLeaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdf
 
Hemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptxHemoglobin metabolism_pathophysiology.pptx
Hemoglobin metabolism_pathophysiology.pptx
 
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of LipidsGBSN - Biochemistry (Unit 5) Chemistry of Lipids
GBSN - Biochemistry (Unit 5) Chemistry of Lipids
 
Orion Air Quality Monitoring Systems - CWS
Orion Air Quality Monitoring Systems - CWSOrion Air Quality Monitoring Systems - CWS
Orion Air Quality Monitoring Systems - CWS
 
Cancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate PathwayCancer cell metabolism: special Reference to Lactate Pathway
Cancer cell metabolism: special Reference to Lactate Pathway
 
Richard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlandsRichard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlands
 
Comparative structure of adrenal gland in vertebrates
Comparative structure of adrenal gland in vertebratesComparative structure of adrenal gland in vertebrates
Comparative structure of adrenal gland in vertebrates
 
Richard's entangled aventures in wonderland
Richard's entangled aventures in wonderlandRichard's entangled aventures in wonderland
Richard's entangled aventures in wonderland
 
erythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptxerythropoiesis-I_mechanism& clinical significance.pptx
erythropoiesis-I_mechanism& clinical significance.pptx
 
Lateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensiveLateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensive
 

Topological Sort Algorithm.pptx

  • 2. Topological Sort •It is a Linear ordering of its vertices such that for every directed edge uv for Vertex u to v , u comes before vertex v in the ordering. •Graph Should be Directed Acyclic Graph (DAG) •Every DAG will have atleast one Topological Ordering
  • 3. What is Directed Acyclic Graph(DAG) • All rooted trees have a topological ordering since the do not contain any cycle. • Topological Ordering • Picking from the bottom once root of subtree has create out children the procedure continues so that we have no node’’ • In DFS, we print a vertex and then recursively call DFS for its adjacent vertices. In topological sorting, we need to print a vertex before its adjacent vertices.
  • 4. Real Life Example Some other applications of the topological sort are manufacturing workflows, project management technique, context-free grammar Course Schedule problem There are some courses and they may have some prerequisite courses. One can finish courses in some order. Prerequisites of course:
  • 5. Algorithm of Topological Sort In topological sorting, •We use a temporary stack. •We don’t print the vertex immediately, •we first recursively call topological sorting for all its adjacent vertices, then push it to a stack. •Finally, print the contents of the stack. Note: A vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so on) are already in the stack
  • 6. Algorithm of Topological Sort 1 3 0 B 2 5 4 0 1 2 3 1 / / 3 / 1 / 0 / 4 5 0 / 2 0 • False 1 • False 3 • False 4 • False 5 • False An adjacency list (based on In-degree) An Empty Stack
  • 7. Algorithm of Topological Sort 0 1 Step -1 0 0 1 3 2 0 1 2 3 1 / / 3 / 1 / 0 / 4 5 0 / 2 Topological Sort (0) , Visited [0] = true Adjacent List is Empty No More recursion CALL Topological Sort (1) , Visited [1] = true Adjacent List is Empty No More recursion call Step -2 Step -3 Topological Sort (2) , Visited [2] = true Topological Sort (3) , Visited [3] = true “1” is already Visited No More recursion call
  • 8. Algorithm of Topological Sort 0 1 3 2 4 5 Step -4 0 1 3 2 4 5 4 3 2 1 0 0 1 2 3 1 / / 3 / 1 / 0 / 4 5 0 / 2 Topological Sort (4) , Visited [4] = true “0” ,“1” are already Visited No More recursion call Topological Sort (5) , Visited [5] = true “2” ,“0” are already Visited No More recursion call Step -5 Step -3 Print all elements of stack from top to bottom Topological Sort of the given graph
  • 9. Pseudocode of Topological Sort topoSort(int u, bool visited[], stack<int>&stk) { visited[u] = true; //set as the node v is visited for(int v = 0; v<NODE; v++) { if(graph[u][v]) { //for all vertices v adjacent to u if(!visited[v]) topoSort(v, visited, stk); } } stk.push(u); //push starting vertex into the stack }
  • 10. Computer Science Application System Deadlock Dependency resolution Here B is the subclass of A and A is the subclass of B. This relationship is not possible. Java compiler shows an error message
  • 11. Complexities • Time Complexity: O(V + E) where V = Vertices, E = Edges. • To determine the in-degree of each node, we will have to iterate through all the edges of the graph. So the time complexity of this step is O(E). • Next, look for nodes with in-degrees equal to 0. This will require us to iterate through the entire array that stores the in-degrees of each node. The size of this array is equal to V. So, the time complexity of this step is O(V). • Auxiliary space: O(V), We have to create one array to store the in- degrees of all the nodes. This will require O(V) space.
  • 12. Advantages • Requires linear time and linear space to perform. • Effective in detecting cyclic dependencies. • Can efficiently find feedback loops that should not exist in a combinational circuit. • Can be used to find the shortest path between two nodes in a DAG in linear time.
  • 13. Disadvantages Topological sort is not possible for a graph that is not directed and acyclic.

Editor's Notes

  1. https://iq.opengenus.org/applications-of-topological-sort/
  2. https://www.geeksforgeeks.org/topological-sorting/
  3. https://www.geeksforgeeks.org/topological-sorting/
  4. https://www.geeksforgeeks.org/topological-sorting/
  5. https://www.interviewkickstart.com/learn/topological-sort#:~:text=The%20time%20complexity%20of%20topological,the%20edges%20of%20the%20graph.