gives a list of vertices of g in topologically sorted order for a directed acyclic graph g.
TopologicalSort[{vw,…}]
uses rules vw to specify the graph g.
TopologicalSort
gives a list of vertices of g in topologically sorted order for a directed acyclic graph g.
TopologicalSort[{vw,…}]
uses rules vw to specify the graph g.
Details
- TopologicalSort is also known as topological ranking or topological ordering.
- A list of vertices is topologically sorted if u precedes v for each edge uv.
Examples
open all close allBasic Examples (1)
Scope (6)
TopologicalSort works with directed graphs:
TopologicalSort[[image]]TopologicalSort[[image]]TopologicalSort[[image]]TopologicalSort only works with acyclic graphs:
TopologicalSort /@ {[image], [image]}Use rules to specify the graph:
TopologicalSort[{1 -> 3, 1 -> 4, 2 -> 1, 2 -> 4, 3 -> 4, 5 -> 2, 5 -> 3}]adj = SparseArray[{i_, j_} /; j > i :> If[RandomReal[] < 0.05, 1, 0], {10^3, 10^3}];
ind = RandomSample[Range[Length[adj]], Length[adj]];
g = AdjacencyGraph[adj[[ind, ind]]];Timing[TopologicalSort[g]//Length]{VertexCount[g], EdgeCount[g]}Applications (1)
Sort strongly connected components instead of vertices when there are cycles:
g = [image];components = ConnectedComponents[g]Construct the condensation of g by finding the edges between the components:
edges = Union[Cases[EdgeList[g] /. Table[v -> First[Select[components, MemberQ[#, v]&]], {v, VertexList[g]}], u_v_ /; u =!= v]];cond = Graph[components, edges]Use the topological ordering of the strongly connected components to order the vertices of g:
TopologicalSort[cond]h = Graph[Join@@%, EdgeList[g], Options[g]]The new adjacency matrix is block upper triangular:
ArrayPlot /@ {AdjacencyMatrix[g], AdjacencyMatrix[h]}See Also
Related Guides
Text
Wolfram Research (2010), TopologicalSort, Wolfram Language function, https://reference.wolfram.com/language/ref/TopologicalSort.html (updated 2015).
CMS
Wolfram Language. 2010. "TopologicalSort." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2015. https://reference.wolfram.com/language/ref/TopologicalSort.html.
APA
Wolfram Language. (2010). TopologicalSort. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/TopologicalSort.html
BibTeX
@misc{reference.wolfram_2026_topologicalsort, author="Wolfram Research", title="{TopologicalSort}", year="2015", howpublished="\url{https://reference.wolfram.com/language/ref/TopologicalSort.html}", note=[Accessed: 13-June-2026]}
BibLaTeX
@online{reference.wolfram_2026_topologicalsort, organization={Wolfram Research}, title={TopologicalSort}, year={2015}, url={https://reference.wolfram.com/language/ref/TopologicalSort.html}, note=[Accessed: 13-June-2026]}