File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ ---
2+ layout : post
3+ title : Topological Sort (coffeescript)
4+ published : true
5+ category : nosql
6+ tags : [algorithm, maizi]
7+ ---
8+
9+ {% highlight coffeescript %}
10+ # topological sort
11+ top_sort:()->
12+ result = [ ] #sort result
13+
14+ node_wrapers = {} #sorting data structure
15+ for node in @nodes
16+ node_wrapers[ node.id] = #initialize the data stucture of each node
17+ node : node
18+ to : [ ] #the nodes that has an edge from this node
19+ visit: 0 #not visited
20+ for link in @links
21+ node_wrapers[ link.source.id] .to.push node_wrapers[ link.target.id]
22+
23+ #visit function for top sort
24+ visit = (node)->
25+ if node.visit is 1 #has a temporary mark
26+ throw "Found a circle"
27+ if node.visit == 0
28+ node.visit = 1 #mark n temporarily
29+ for to_node in node.to
30+ visit to_node
31+ node.visit = 2 #mark n permanently
32+ result.push node.node
33+
34+
35+ for node_id, node of node_wrapers
36+ if(node.visit == 0)
37+ visit(node)
38+ return result
39+
40+ {% endhighlight %}
You can’t perform that action at this time.
0 commit comments