Topological Sort

A topological sort(ing) of a directed graph G=(V,E) is an ordering of its vertices as V={u0,,un1} such that for all edges (ui,uj) we have i<j

TOPOLOGICAL SORTING

Given: A directed graph G=(V,E)
Return: A topological sorting of G or "Impossible" if none exists

Warning

A directed graph is cyclic if and only if it has no topological sorting

begin topSort(G)
	compute all in-degress and store in G.inDeg
	let S be a stack and i = 0, arr = []
	for each v in G.vertices
		if G.inDeg(v) = 0 then push v on stack S
	while stack S is non-empty:
		v = pop(S)
		arr[i] = v
		i++
		for each w in G.edges(v) do
			decrement G.inDeg(w)
			if G.inDeg(w) = 0 then push w on stack S
	if i = n
		return arr
	return "Impossible"