Skip to content

Commit abeee9c

Browse files
committed
Added Kahn's Algorithm (Topological Sort) in JavaScript
1 parent 08d8c6b commit abeee9c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Graphs/KahnsAlgorithm.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Kahn's Algorithm for Topological Sort
2+
function kahnTopologicalSort(vertices, edges) {
3+
const adj = new Map();
4+
const indegree = new Array(vertices).fill(0);
5+
6+
// Build adjacency list & indegree count
7+
for (let [u, v] of edges) {
8+
if (!adj.has(u)) adj.set(u, []);
9+
adj.get(u).push(v);
10+
indegree[v]++;
11+
}
12+
13+
const queue = [];
14+
for (let i = 0; i < vertices; i++) {
15+
if (indegree[i] === 0) queue.push(i);
16+
}
17+
18+
const topo = [];
19+
while (queue.length > 0) {
20+
const node = queue.shift();
21+
topo.push(node);
22+
23+
if (adj.has(node)) {
24+
for (let neigh of adj.get(node)) {
25+
indegree[neigh]--;
26+
if (indegree[neigh] === 0) queue.push(neigh);
27+
}
28+
}
29+
}
30+
31+
if (topo.length !== vertices) {
32+
throw new Error("Graph has a cycle, topological sort not possible");
33+
}
34+
35+
return topo;
36+
}
37+
38+
// Example usage
39+
const vertices = 6;
40+
const edges = [[5,2],[5,0],[4,0],[4,1],[2,3],[3,1]];
41+
console.log("Topological Sort:", kahnTopologicalSort(vertices, edges));

0 commit comments

Comments
 (0)