Post

Topological Sort in Java

Learn how Topological Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.

Topological Sort in Java

Introduction

Topological Sort is a graph algorithm. It takes a directed acyclic graph (DAG), where an edge from u to v means “u must come before v”, and puts all the vertices in one line so that every edge points forward. It doesn’t sort values by size; it sorts tasks by their dependencies.

Three ideas carry the whole algorithm:

  • Depth-first search: from each vertex, follow its edges as deep as possible before backing up.
  • Finish order: a vertex is finished once every vertex it leads to has been finished. Adding each finished vertex to the front of a list puts it before everything that depends on it.
  • Three colours: WHITE for not visited, GRAY for on the current search path, BLACK for finished. Reaching a GRAY vertex means the graph has a cycle, and no valid order exists.

Topological sorting is everywhere that work has dependencies. Build tools such as Maven and Gradle use it to decide which modules to compile first, package managers to install dependencies before the packages that need them, spreadsheets to recalculate cells in the right order, and schedulers to order tasks. A graph usually has many valid orders, and any one of them will do.

This article uses the DFS-based topological sort with WHITE, GRAY and BLACK colours, as described in Introduction to Algorithms (CLRS), with cycle detection through back edges.

Performance Characteristics

Topological Sort visits every vertex and follows every edge exactly once, so its cost depends only on the size of the graph, not on its shape.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

In the table, $V$ is the number of vertices and $E$ the number of edges.

CaseTimeWhen it happens
Best$O(V + E)$Any DAG: every vertex is visited once and every edge is followed once
Average$O(V + E)$Any DAG
Worst$O(V + E)$Any DAG; a graph with a cycle stops early at the first back edge

Why $V + E$? A vertex is visited only while it is WHITE, and it turns GRAY straight away, so each vertex starts a visit at most once. Each visit walks through that vertex’s own edges once, so across the whole search every edge is looked at exactly once.

If you need a specific order among the valid ones, for example the alphabetically smallest, use Kahn’s algorithm instead: it repeatedly removes a vertex with no incoming edges, and with a priority queue it picks the smallest one each time. It also avoids recursion.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(V)$ for the colours, the result list and the recursion stack, which can be $V$ deep
In placeNo (the result is a new list of vertex labels)

Algorithm (Pseudo Code)

Topological Sort goes through the vertices one by one. When it finds a vertex that hasn’t been visited, it starts a depth-first search there: it marks the vertex GRAY and follows each of its edges. A WHITE vertex at the other end is visited the same way, deeper and deeper. A BLACK vertex is already finished and is skipped. When all edges of a vertex have been followed, the vertex is finished: it turns BLACK and is added to the front of the result list.

A vertex only finishes after everything it leads to has finished, so it is always added in front of all of them. When the outer loop has tried every vertex, all vertices are BLACK and the list holds a valid order. If the search ever follows an edge to a GRAY vertex, that vertex is still on the current path, so the edge closes a loop, and the sort stops with an error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
sort(graph):
    list = empty list
    for each vertex u in graph:
        if u.color == WHITE:
            list.addFirst(visit(graph, u, list))
    return list

visit(graph, u, list):
    u.color = GRAY
    for each v in u.next:
        if v.color == WHITE:
            list.addFirst(visit(graph, v, list))
        else if v.color == GRAY:
            throw "cycle: back edge u -> v"
    u.color = BLACK
    return u.label

When a vertex turns BLACK, every vertex it can reach is already in the list, so putting it at the front keeps every edge pointing forward.

A BLACK neighbour is not a cycle: it is a vertex that was finished earlier, perhaps by another branch of the search, and it is already in the list behind the current vertex. Only a GRAY neighbour, one on the current path, closes a loop.

Visualization

The visualization below follows the Java code line by line, starting with the “getting dressed” graph from CLRS: nine pieces of clothing, with an edge wherever one has to go on before another.

Each step shows the graph, the current search path, the result list and the line of code that is running, with a short explanation of what just happened:

  • Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
  • Play: press Play to run the steps automatically, and press it again to pause.
  • Shuffle: press the shuffle button to add the vertices and their edges in a new random order. The graph stays the same, but the search visits it in a different order and usually finds a different valid result.
  • Colours: WHITE vertices are not visited yet, GRAY vertices (amber) are on the current path, and BLACK vertices (green) are finished. The edge being followed is salmon, and the vertex being worked on has a dark outline.
  • Path and list: the path row shows the GRAY vertices, from where the search started to where it is now. The list row is the result, built from the front.
  • Add a cycle: tick Add jacket → shirt to add an edge that creates a cycle, and see the sort detect it and throw.
WHITE: not visited GRAY: on the path BLACK: finished edge being followed

Java Code

The implementation is a TopologicalSort utility class: it is final, has a private constructor, and offers one public static method, sort(Graph). The search itself is a private overload, sort(Graph, Vertex, LinkedList), which visits one vertex. Three nested types hold the graph: Graph with its addEdge method stores an adjacency list, Vertex stores a label, a colour and the labels of its neighbours, and the Color enum provides WHITE, GRAY and BLACK. The class doesn’t use the SortUtils helpers.

The complete code is in the algorithm-examples repository on GitHub: TopologicalSort.java.

sort(Graph)

1
2
3
4
5
6
7
8
9
public static LinkedList<String> sort(Graph graph) {
    LinkedList<String> list = new LinkedList<>();
    graph.adj.forEach((name, vertex) -> {
        if (vertex.color == Color.WHITE) {
            list.addFirst(sort(graph, vertex, list));
        }
    });
    return list;
}

sort(Graph) is the entry point. It creates the result list and walks through every vertex in the order it was added to the graph. Each vertex that is still WHITE starts a new depth-first search, and when that search returns the vertex’s label, the label goes to the front of the list. Vertices that an earlier search already finished are BLACK and are skipped. A LinkedList makes addFirst an $O(1)$ operation.

The colours are stored in the Vertex objects and are never reset. After one sort, every vertex is BLACK, so calling sort on the same Graph again returns an empty list. After a cycle exception, some vertices are left GRAY. Keeping the colours in a local Map<String, Color> inside sort makes the method safe to call more than once.

sort(Graph, Vertex, LinkedList)

1
2
3
4
5
6
7
8
9
10
11
12
private static String sort(Graph graph, Vertex u, LinkedList<String> list) {
    u.color = Color.GRAY;
    graph.adj.get(u.label).next.forEach(label -> {
        if (graph.adj.get(label).color == Color.WHITE) {
            list.addFirst(sort(graph, graph.adj.get(label), list));
        } else if (graph.adj.get(label).color == Color.GRAY) {
            throw new RuntimeException("This graph contains a cycle. No linear ordering is possible. Back edge: " + u.label + " -> " + label);
        }
    });
    u.color = Color.BLACK;
    return u.label;
}

The private overload visits the vertex u. It marks u GRAY, then looks up each neighbour by its label. A WHITE neighbour is visited recursively, and its label goes to the front of the list as soon as that visit returns. A GRAY neighbour is on the current path, so the edge is a back edge and the method throws a RuntimeException that names it. A BLACK neighbour needs nothing. When every neighbour has been handled, u turns BLACK and its label is returned, so the caller can add it to the front of the list.

Two details are worth noticing:

  • The method returns the label instead of adding it itself, so the addFirst happens in the caller. The effect is the same: a vertex goes into the list right after its last descendant, and in front of it.
  • The recursion goes as deep as the longest path in the graph. With the default JVM stack, a chain of 1,000 dependencies sorts fine, but a chain of 5,000 already ends in a StackOverflowError, because every level adds the forEach lambda frames as well. An iterative search with an explicit stack, or Kahn’s algorithm, avoids that.

Graph and addEdge

1
2
3
4
5
6
7
8
9
10
11
static class Graph {

    private final HashMap<String, Vertex> adj = new LinkedHashMap<>();

    public void addEdge(String label, String... next) {
        adj.put(label, new Vertex(label));
        if (!next[0].isEmpty()) {
            Collections.addAll(adj.get(label).next, next);
        }
    }
}

Graph stores the vertices in a LinkedHashMap from label to Vertex, so the outer loop always visits them in the order they were added. addEdge adds a vertex together with all of its outgoing edges in one call: addEdge("shirt", "tie", "belt") means shirt comes before tie and belt. A vertex without outgoing edges is added with an empty string, as in addEdge("jacket", "").

addEdge is easy to misuse. Calling it twice for the same label replaces the vertex, and the edges from the first call are lost. Calling it without a second argument, as in addEdge("watch"), throws an ArrayIndexOutOfBoundsException on next[0]. And every label used as a target must also be added as a vertex of its own; otherwise graph.adj.get(label) returns null and the sort throws a NullPointerException. Graph is also package-private, so code outside com.javanibble.sort can’t create one, even though sort is public.

Vertex and Color

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private enum Color {
    WHITE,
    GRAY,
    BLACK,
}

private static class Vertex {

    public final String label;

    public Color color = Color.WHITE;

    public final ArrayList<String> next = new ArrayList<>();

    Vertex(String label) {
        this.label = label;
    }
}

Vertex holds the label, the current colour, which starts as WHITE, and the labels of the vertices it has edges to. The edges store labels, not Vertex references, which is why the search looks every neighbour up in graph.adj. Color names the three states of the depth-first search.

Running it

1
2
3
4
5
6
7
8
9
10
11
12
TopologicalSort.Graph graph = new TopologicalSort.Graph();
graph.addEdge("shirt", "tie", "belt");
graph.addEdge("tie", "jacket");
graph.addEdge("pants", "shoes", "belt");
graph.addEdge("shoes", "");
graph.addEdge("socks", "shoes");
graph.addEdge("jacket", "");
graph.addEdge("belt", "jacket");
graph.addEdge("watch", "");
graph.addEdge("undershorts", "pants", "shoes");
System.out.println(TopologicalSort.sort(graph));
// [undershorts, watch, socks, pants, shoes, shirt, belt, tie, jacket]

Build the graph with one addEdge call per vertex, then call sort. This is the graph from the visualization, and the output is the same order. The code must be in the com.javanibble.sort package, because Graph is package-private.

Summary

  • Topological Sort orders the vertices of a directed acyclic graph so that every edge points forward: each task comes before the tasks that depend on it.
  • This implementation is a depth-first search with WHITE, GRAY and BLACK colours: every finished vertex is added to the front of a linked list.
  • When a vertex turns BLACK, everything it leads to is already in the list behind it, and an edge to a GRAY vertex is a back edge that proves a cycle.
  • It runs in $O(V + E)$ time and needs $O(V)$ extra space, including a recursion stack as deep as the longest path.
  • The colours live in the graph, so a graph can only be sorted once, and addEdge replaces vertices. For large or deep graphs, or when you need a specific order, use Kahn’s algorithm with a queue or a priority queue.
This post is licensed under CC BY 4.0 by the author.