[Verse 1] Got a graph with arrows pointing every way Dependencies tangled like a web today Need an order that respects the flow Start with nodes that have no arrows coming home Kahn's algorithm is the way to go Queue up vertices with indegree zero Remove them one by one and update the count Linear ordering is what it's all about [Chorus] Topological sort, gotta respect the order No cycles allowed, that's the golden border Directed acyclic graph is what we need Follow dependencies, let the sorting lead In-degree zero, that's where we start Remove and repeat, it's algorithmic art [Verse 2] Depth first search gives another route Visit nodes deep, mark them on the way out Finish time tells us the reverse rank Stack them up as each traversal ends blank If you hit a back edge, cycle's found Topological order can't be crowned Prerequisites must come before their class Like compiling code, respect what has to pass [Chorus] Topological sort, gotta respect the order No cycles allowed, that's the golden border Directed acyclic graph is what we need Follow dependencies, let the sorting lead In-degree zero, that's where we start Remove and repeat, it's algorithmic art [Bridge] Course scheduling, task management flow Build systems need to know which way to go Deadlock detection, dependency chains Linear time complexity, algorithmic gains Two methods same result, choose your style Kahn or DFS, both worthwhile [Verse 3] Implementation time, let's break it down Adjacency list keeps the data sound Count incoming edges for each node Queue or stack depending on your code Time complexity is big O of V plus E Vertices and edges, that's the key Space is linear, efficient and clean Best sorting algorithm you've ever seen [Outro] When dependencies rule your data game Topological sort will stake its claim No cycles, just order, respect the flow That's how the algorithm's supposed to go
← A* search | Tarjan's algorithm (strongly connected components) →