Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Topological Sort
directed graphs
  • Loading branch information
NourBennour authored Apr 19, 2020
commit 9fe41bb219af87601512edf756489977c1e29c86
59 changes: 59 additions & 0 deletions Sorts/TopologicalSort,js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
function TopologicalSorter() {
var graph = {},
isVisitedNode,
finishTimeCount,
finishingTimeList,
nextNode;

this.addOrder = function (nodeA, nodeB) {
nodeA = String(nodeA);
nodeB = String(nodeB);
graph[nodeA] = graph[nodeA] || [];
graph[nodeA].push(nodeB);
}

this.sortAndGetOrderedItems = function () {
isVisitedNode = Object.create(null);
finishTimeCount = 0;
finishingTimeList = [];

for (var node in graph) {
if (graph.hasOwnProperty(node) && !isVisitedNode[node]) {
dfsTraverse(node);
}
}

finishingTimeList.sort(function (item1, item2) {
return item1.finishTime > item2.finishTime ? -1 : 1;
});

return finishingTimeList.map(function (value) { return value.node })
}

function dfsTraverse(node) {
isVisitedNode[node] = true;
if (graph[node]) {
for (var i = 0; i < graph[node].length; i++) {
nextNode = graph[node][i];
if (isVisitedNode[nextNode]) continue;
dfsTraverse(nextNode);
}
}

finishingTimeList.push({
node: node,
finishTime: ++finishTimeCount
});
}
}


/* TEST */
var topoSorter = new TopologicalSorter();
topoSorter.addOrder(5, 2);
topoSorter.addOrder(5, 0);
topoSorter.addOrder(4, 0);
topoSorter.addOrder(4, 1);
topoSorter.addOrder(2, 3);
topoSorter.addOrder(3, 1);
console.log(topoSorter.sortAndGetOrderedItems());