Topological Sorting
2 min readMay 5, 2021
Explain what topological sorting is and how it is implemented.
What is topological sorting?
Topological sorting is used only on Directed Acyclic Graphs(DAG) and is used to produce a linear ordering of vertices such that for all edges (u, v), u always appears before v. The result is not always unique.
Quick Solution
- The first step is to identify a node that has an in-degree of 0, there can be multiple. If there are none in the graph, then the graph has cycles.
- After identifying a node with an in-degree of 0, the node, and all of its outgoing edges should be removed.
- Repeat steps 1 and 2 until the graph is empty.
In-Depth Solution
- The function should take in one parameter being the directed acyclic graph.
- Generate a vector that contains the in-degree of all vertices in the graph.
- While the graph still has vertices do the following
- Get the next vertex with an in-degree of 0. Let it be called U.
- Remove U and its outgoing edges from the graph.
- Set in_degree_vector[u] to -1 to show that it has been removed from the graph.
- Repeat steps 4–6 until the graph is empty.