Files
dsa-tutoring/notes-and-examples/2026.08.27/topological_sort.md

1.1 KiB

Class ordering

These are some classes for Chapman University, for the computer science program.

An ordering of classes for Chapman University.

This is a directed acyclic graph, or DAG.

  • Directed: edges point from one node to another, not necessarily the other way around
  • Acyclic: there are no cycles in the graph

We say that a class is a prerequisite or a dependency of another class if we need to take it before that other class. So, we need to take CPSC 230 before CPSC 231, for example.

Could you come up with something like this for your school?

The algorithm

If you were to come up with a list of classes, such that the list of classes is in the order which you need to take them, what would that look like?

This order is what we're trying to achieve with the topological sort algorithm. Note that there can be multiple correct solutions.

The exercise

Let's write the algorithm. First, test it against the Chapman classes, then put in your classes and see how it fares against that.