1 // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle
.Core
.Internal
17 using System
.Diagnostics
;
19 public abstract class TopologicalSortAlgo
21 public static IVertex
[] Sort(IVertex
[] graphNodes
)
23 ColorsSet colors
= new ColorsSet(graphNodes
);
24 TimestampSet discovery
= new TimestampSet();
25 TimestampSet finish
= new TimestampSet();
26 LinkedList list
= new LinkedList();
30 foreach(IVertex node
in graphNodes
)
32 if (colors
.ColorOf(node
) == VertexColor
.White
)
34 Visit(node
, colors
, discovery
, finish
, list
, ref time
);
38 return (IVertex
[]) list
.ToArray(typeof(IVertex
));
41 private static void Visit(IVertex node
, ColorsSet colors
,
42 TimestampSet discovery
, TimestampSet finish
, LinkedList list
, ref int time
)
44 colors
.Set(node
, VertexColor
.Gray
);
46 discovery
.Register(node
, time
++);
48 foreach(IVertex child
in node
.Adjacencies
)
50 if (colors
.ColorOf(child
) == VertexColor
.White
)
52 Visit(child
, colors
, discovery
, finish
, list
, ref time
);
56 finish
.Register(node
, time
++);
59 Debug
.Assert(discovery
.TimeOf(node
) < finish
.TimeOf(node
));
64 colors
.Set(node
, VertexColor
.Black
);