Comparing Topological Sort Loop-based and Recursive Implementations

Hair Parra
6 min readMar 21, 2023

With examples in Java and Python

A graph topoplogical sort (Img src: https://leetcode.com/discuss/general-discussion/1078072/introduction-to-topological-sort)

Topological Sort is an algorithm used to order the vertices of a directed graph in a way that satisfies its dependencies. It has numerous applications in computer science, including scheduling tasks, detecting deadlocks, and resolving dependencies between software modules.

In this article, we’ll dive into the implementation of Topological Sort in Java, exploring two different approaches — one using a loop-based method, and another using recursion. We’ll provide detailed code examples with comments to help you understand each step of the algorithm.

But this article is more than just code — we’ll also compare the time and space complexity of both approaches and discuss when to use one over the other depending on the characteristics of the graph being processed.

So if you’re looking to learn more about Topological Sort in Java and want to deepen your understanding of its implementation, join us on this journey as we explore the nuances of this fascinating algorithm.

So sit back, relax, and let me guide you through this informative journey on Topological Sort in Java!

Example

Src: https://en.wikipedia.org/wiki/File:Directed_acyclic_graph_2.svg

In this example, provided in the Wikipedia article, the graph above has many valid topological sorts, including:

  • 5, 7, 3, 11, 8, 2, 9, 10 (visual top-to-bottom, left-to-right)
  • 3, 5, 7, 8, 11, 2, 9, 10 (smallest-numbered available vertex first)
  • 5, 7, 3, 8, 11, 10, 9, 2 (fewest edges first)
  • 7, 5, 11, 3, 10, 8, 9, 2 (largest-numbered available vertex first)
  • 5, 7, 11, 2, 3, 8, 9, 10 (attempting top-to-bottom, left-to-right)
  • 3, 7, 8, 5, 11, 10, 2, 9 (arbitrary)

Kahn’s Algorithm

Kahn’s Algorithm is a popular algorithm for performing a topological sort on a directed acyclic graph (DAG). It works by finding nodes in the graph that have no incoming edges and adding them to a queue. As…

--

--

Hair Parra

Data Scientist & Data Engineer. CS, Stats & Linguistics graduate. Polyglot.