%% Stable Topological Sort
% Create a directed graph using a logical adjacency matrix, and then plot the graph.

rng default;
A = tril(sprand(10, 10, 0.3), -1)~=0;
G = digraph(A);
[~,G] = toposort(G);
plot(G)

%
% Find the topological sorting of the graph nodes. Even though G is already in topological order, (1 2 3 4 5 6 7 8 9 10), toposort reorders the nodes.

toposort(G)

%
% Specify Order as 'stable' to use the stable ordering algorithm, so that the sort orders the nodes with smaller indices first. Stable sort does not rearrange G if it is already in topological order.

toposort(G,'Order','stable')

% Copyright 2015 The MathWorks, Inc.