Skip to content

Instantly share code, notes, and snippets.

@robrighter
Created May 6, 2011 21:19
Show Gist options
  • Save robrighter/959803 to your computer and use it in GitHub Desktop.
Save robrighter/959803 to your computer and use it in GitHub Desktop.
Topological Sort in Javascript
var assert = require('assert');
var topologicalSort = require('./topologicalsort').topologicalSort;
tests = [
{
graph: [
{edges:[1,2]},
{edges:[3]},
{edges:[5]},
{edges:[4]},
{edges:[5,6]},
{edges:[6]},
{edges:[]}
],
solution: [0,1,2,3,4,5,6]
},
{
graph: [
{edges:[1,2]},
{edges:[3]},
{edges:[1,4]},
{edges:[5]},
{edges:[5,6]},
{edges:[7]},
{edges:[7]},
{edges:[]}
],
solution: [ 0, 2, 1, 4, 3, 6, 5, 7 ]
},
{
graph: [
{edges:[1,2]},
{edges:[3]},
{edges:[1,4]},
{edges:[5]},
{edges:[5,6]},
{edges:[7]},
{edges:[7]},
{edges:[0]}
],
solution: 'cycle'
}
];
var counter = 0;
tests.forEach(function(graph){
console.log('GRAPH ' + counter++);
console.log(graph.graph);
try{
var solution = topologicalSort(graph.graph);
assert.deepEqual(solution, graph.solution);
console.log('Succesfully Solved With:');
console.log(solution);
}catch(e){
if((e === "You have a cycle!!") && (graph.solution==='cycle')){
console.log('Succesfully Detected Cycle.');
}
else{
console.log('DID NOT PASS TESTS!!!');
}
}
console.log('-------------------------------------------');
});
function topologicalSort(graph){
var processed = [];
var queue = [];
populateIndegrees();
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
}
}
processStartingPoint(queue.shift());
if(processed.length<graph.length){
processList();
}
}
function processStartingPoint(i){
if(i == undefined){
throw "You have a cycle!!";
}
graph[i].edges.forEach(function(e){
graph[e].indegrees--;
});
processed.push(i);
}
function populateIndegrees(){
for(var i=0; i<graph.length; i++){
if(!graph[i].hasOwnProperty('indegrees')){
graph[i].indegrees = 0
}
graph[i].edges.forEach(function(e){
if(!graph[e].hasOwnProperty('indegrees')){
graph[e].indegrees = 1
}
else{
graph[e].indegrees = graph[e].indegrees + 1;
}
});
}
}
}
module.exports.topologicalSort = topologicalSort;
@robrighter
Copy link
Author

This code has been moved into its own github project. Please track updates at that location:
https://github.com/robrighter/javascript-topological-sort

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment