Complexity | Note | |
---|---|---|
Worst Time: | O(E + V) | Initialisation takes O(E+V), inner loop takes O(E + V) |
Worst Space: | O(E + V) | Using an adjacency list |
- Initialise two lists:
L
, to hold the sorted elementsS
, all the vertices in the graph with no incoming edges
- repeat until
S
is empty:- remove a vertex
n
fromS
- append
n
toL
- for every vertex
m
thatn
connects to (i.e.n
→m
)- remove all of
m
's connections fromn
- then add
m
toS
- remove all of
- remove a vertex
- Return
L
L = Empty list that will contain the sorted elements
S = Set of all nodes with no incoming edges
while S is non-empty
remove a node n from S
append n to L
for each node m with an edge e from n to m
remove edge e from graph
if m has no other incoming edges then
insert m into S
if graph has edges after above then
return error (graph has at least one cycle)
else
return L (a topologically sorted order)