Code Implementation
Here is the code implementation for the topological sort:
xxxxxxxxxx35
console.log(sortedNodes.slice(0, -1));let nodesList = [[1, 2], [2, 3], [2, 5], [3, 4], [3, 5]];let nodes = nodesList.length + 1;​let adjacentNodes = Array.from({ length: nodes }, () => []);let visitedNodes = Array.from({ length: nodes }, () => false);let sortedNodes = [];​function createEdge(nodeA, nodeB) { adjacentNodes[nodeA].push(nodeB);}​function sortArr(node) { visitedNodes[node] = true; for (let each of adjacentNodes[node]) { if (!visitedNodes[each]) { sortArr(each); } }​ sortedNodes.push(node);}​for (let node of nodesList) { createEdge(node[0], node[1]);}​for (let item = 0; item < nodes; item++) { if (!visitedNodes[item]) { sortArr(item);OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


