-
-
Notifications
You must be signed in to change notification settings - Fork 30.6k
/
Copy pathkruskal.js
40 lines (34 loc) · 1.3 KB
/
kruskal.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import Graph from '../../../data-structures/graph/Graph';
import QuickSort from '../../sorting/quick-sort/QuickSort';
import DisjointSet from '../../../data-structures/disjoint-set/DisjointSet';
/**
* @param {Graph} graph
* @return {Graph}
*/
export default function kruskal(graph) {
// Check for directed graph
if (graph.isDirected) {
throw new Error("Kruskal's algorithm works only for undirected graphs");
}
// Initialize the MST graph
const minimumSpanningTree = new Graph();
// Sort all edges by weight in ascending order
const sortedEdges = new QuickSort({
/**
* @param {GraphEdge} graphEdgeA
* @param {GraphEdge} graphEdgeB
*/
compareCallback: (graphEdgeA, graphEdgeB) => graphEdgeA.weight - graphEdgeB.weight,
}).sort(graph.getAllEdges());
// Initialize disjoint sets for vertices
const disjointSet = new DisjointSet((vertex) => vertex.getKey());
graph.getAllVertices().forEach((vertex) => disjointSet.makeSet(vertex));
// Add edges to the MST if they don’t form a cycle
for (const currentEdge of sortedEdges) {
if (!disjointSet.inSameSet(currentEdge.startVertex, currentEdge.endVertex)) {
disjointSet.union(currentEdge.startVertex, currentEdge.endVertex);
minimumSpanningTree.addEdge(currentEdge);
}
}
return minimumSpanningTree;
}