Stable topological sort

Puts the vertices of a graph without cycles in an order where every edge points forward, taking the ready vertex that comes first alphabetically.

Time complexity O((V+E) log V), gograph function gograph.StableTopologySort.

Course prerequisites

Fourteen courses of a computer science degree. Each edge points from a course to a course that requires it.

A directed graph with 14 vertices and 18 edges.

In what order can a student take the courses, so that every course comes after the courses it requires?

Use it in Go

order, err := gograph.StableTopologySort(g, cmp.Compare)
if err != nil {
	return err // gograph.ErrDAGHasCycle
}
for _, v := range order {
	fmt.Println(v.Label())
}

Example graphs

More in Ordering

  • Topological sort: Puts the vertices of a graph without cycles in an order where every edge points forward, taking vertices in the order they become ready.

All algorithms