Mercurial > hg > camir-aes2014
annotate toolboxes/FullBNT-1.0.7/graph/topological_sort.m @ 0:e9a9cd732c1e tip
first hg version after svn
author | wolffd |
---|---|
date | Tue, 10 Feb 2015 15:05:51 +0000 |
parents | |
children |
rev | line source |
---|---|
wolffd@0 | 1 function order = topological_sort(A) |
wolffd@0 | 2 % TOPOLOGICAL_SORT Return the nodes in topological order (parents before children). |
wolffd@0 | 3 % order = topological_sort(adj_mat) |
wolffd@0 | 4 |
wolffd@0 | 5 n = length(A); |
wolffd@0 | 6 indeg = zeros(1,n); |
wolffd@0 | 7 zero_indeg = []; % a stack of nodes with no parents |
wolffd@0 | 8 for i=1:n |
wolffd@0 | 9 indeg(i) = length(parents(A,i)); |
wolffd@0 | 10 if indeg(i)==0 |
wolffd@0 | 11 zero_indeg = [i zero_indeg]; |
wolffd@0 | 12 end |
wolffd@0 | 13 end |
wolffd@0 | 14 |
wolffd@0 | 15 t=1; |
wolffd@0 | 16 order = zeros(1,n); |
wolffd@0 | 17 while ~isempty(zero_indeg) |
wolffd@0 | 18 v = zero_indeg(1); % pop v |
wolffd@0 | 19 zero_indeg = zero_indeg(2:end); |
wolffd@0 | 20 order(t) = v; |
wolffd@0 | 21 t = t + 1; |
wolffd@0 | 22 cs = children(A, v); |
wolffd@0 | 23 for j=1:length(cs) |
wolffd@0 | 24 c = cs(j); |
wolffd@0 | 25 indeg(c) = indeg(c) - 1; |
wolffd@0 | 26 if indeg(c) == 0 |
wolffd@0 | 27 zero_indeg = [c zero_indeg]; % push c |
wolffd@0 | 28 end |
wolffd@0 | 29 end |
wolffd@0 | 30 end |