To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Revision:

root / _FullBNT / BNT / graph / topological_sort.m @ 8:b5b38998ef3b

History | View | Annotate | Download (697 Bytes)

1
function order = topological_sort(A)
2
% TOPOLOGICAL_SORT Return the nodes in topological order (parents before children).
3
% order = topological_sort(adj_mat)
4

    
5
n = length(A);
6
indeg = zeros(1,n);
7
zero_indeg = []; % a stack of nodes with no parents
8
for i=1:n
9
  indeg(i) = length(parents(A,i));
10
  if indeg(i)==0
11
    zero_indeg = [i zero_indeg];
12
  end
13
end
14

    
15
t=1;
16
order = zeros(1,n);
17
while ~isempty(zero_indeg)
18
  v = zero_indeg(1); % pop v
19
  zero_indeg = zero_indeg(2:end);
20
  order(t) = v;
21
  t = t + 1;
22
  cs = children(A, v);
23
  for j=1:length(cs)
24
    c = cs(j);
25
    indeg(c) = indeg(c) - 1;
26
    if indeg(c) == 0
27
      zero_indeg = [c zero_indeg]; % push c 
28
    end
29
  end
30
end