Skip to content
Browse files

performance improvement by not rechecking already processed nodes

  • Loading branch information...
1 parent 9fce2e6 commit 7942608ed14a2c548a14ff43ee24330826304f1d @robrighter committed Feb 25, 2012
Showing with 26 additions and 14 deletions.
  1. +0 −2 README.md
  2. +26 −12 topological-sort.js
View
2 README.md
@@ -4,5 +4,3 @@ Javascript Topological Sort
Implementation of a topological sort in javascript. Topological sorts are useful for determining proper order precedence. To learn more about topological sorting watch this video:
http://video.google.com/videoplay?docid=2755333184412284530
-
-<embed id=VideoPlayback src=http://video.google.com/googleplayer.swf?docid=2755333184412284530&hl=en&fs=true style=width:400px;height:326px allowFullScreen=true allowScriptAccess=always type=application/x-shockwave-flash> </embed>
View
38 topological-sort.js
@@ -1,20 +1,29 @@
function topologicalSort(graph){
+ var numberOfNodes = graph.length;
var processed = [];
+ var unprocessed = [];
var queue = [];
- populateIndegrees();
+ populateIndegreesAndUnprocessed();
processList();
return processed;
function processList(){
- for(var i=0; i<graph.length; i++){
- if(graph[i].indegrees === 0){
- queue.push(i);
- graph[i].indegrees = -1; //dont look at this one anymore
+ var toBeRemoved = [];
+ for(var i=0; i<unprocessed.length; i++){
+ var nodeid = unprocessed[i];
+ if(graph[nodeid].indegrees === 0){
+ queue.push(nodeid);
+ console.log('About to remove edge ' + i + ' from the graph.');
+ unprocessed.splice(i, 1); //Remove this node, its all done.
+ i--;//decrement i since we just removed that index from the iterated list;
}
}
+ console.log(unprocessed);
+ console.log('\n\n');
+
processStartingPoint(queue.shift());
- if(processed.length<graph.length){
+ if(processed.length<numberOfNodes){
processList();
}
}
@@ -24,28 +33,33 @@ function topologicalSort(graph){
if(i == undefined){
throw "You have a cycle!!";
}
- graph[i].edges.forEach(function(e){
+ for( var t=0; t<graph[i].edges.length; t++){
+ var e = graph[i].edges[t];
graph[e].indegrees--;
- });
+ };
processed.push(i);
}
- function populateIndegrees(){
+ function populateIndegreesAndUnprocessed(){
for(var i=0; i<graph.length; i++){
+ unprocessed.push(i);
if(!graph[i].hasOwnProperty('indegrees')){
graph[i].indegrees = 0
}
- graph[i].edges.forEach(function(e){
+ for( var t=0; t<graph[i].edges.length; t++){
+ var e = graph[i].edges[t];
if(!graph[e].hasOwnProperty('indegrees')){
graph[e].indegrees = 1
}
else{
graph[e].indegrees = graph[e].indegrees + 1;
- }
- });
+ }
+ }
}
}
+
+
}

0 comments on commit 7942608

Please sign in to comment.
Something went wrong with that request. Please try again.