MCPcopy Create free account
hub / github.com/TheAlgorithms/TypeScript / kruskal

Function kruskal

graph/kruskal.ts:14–37  ·  view source on GitHub ↗
(
  edges: Edge[],
  num_vertices: number
)

Source from the content-addressed store, hash-verified

12 * @see https://en.wikipedia.org/wiki/Kruskal%27s_algorithm
13 */
14export const kruskal = (
15 edges: Edge[],
16 num_vertices: number
17): [Edge[], number] => {
18 let cost = 0
19 const minimum_spanning_tree = []
20
21 // Use a disjoint set to quickly join sets and find if vertices live in different sets
22 const sets = new DisjointSet(num_vertices)
23
24 // Sort the edges in ascending order by weight so that we can greedily add cheaper edges to the tree
25 edges.sort((a, b) => a.weight - b.weight)
26
27 for (const edge of edges) {
28 if (sets.find(edge.a) !== sets.find(edge.b)) {
29 // Node A and B live in different sets. Add edge(a, b) to the tree and join the nodes' sets together.
30 minimum_spanning_tree.push(edge)
31 cost += edge.weight
32 sets.join(edge.a, edge.b)
33 }
34 }
35
36 return [minimum_spanning_tree, cost]
37}
38
39export class Edge {
40 a: number = 0

Callers 2

test_graphFunction · 0.90
kruskal.test.tsFile · 0.90

Calls 3

findMethod · 0.95
joinMethod · 0.95
pushMethod · 0.65

Tested by 1

test_graphFunction · 0.72