7.3. Topological Sorting
This section discusses two algorithms for topological sorting.
Last updated
Was this helpful?
This section discusses two algorithms for topological sorting.
Last updated
Was this helpful?
The task of topological sorting is to sort vertices in a linear order such that for each vertex, all target vertices associated with its incoming edges must appear prior to it.
The followings demonstrate how to perform a topological sort by incoming scores, where the incoming score of a vertex is define as the sum of all source vertices:
The followings demonstrate how to perform a topological sort by depth-first traversing:
Let us define the topological_sort()
method under the Graph
class that performs topological sort by either incoming scores or depth-first search:
L2
: starts with vertices with no incoming edges.
L3
: retrieves outgoing edges of each source vertex.
L4
: consists of the list of vertices in topological order.
L6
: iterates until no more vertex to visit:
L8-9
: adds a source vertex to order
.
L12
: iterates through all the outgoing edges of the source vertex:
L17
: removes the outgoing edge from the graph.
L20-21
: adds the target vertex if it has no incoming edge left to local
.
L25-27
: adds all vertices in local
to global
.
What is the worst-case complexity of the
topological_sort()
method?