VLVisual Learner

Kruskal's Algorithm (Minimum Spanning Tree)

Time: O(E log E)Space: O(V + E)Greedy · Union-Find
–
Ad

Understanding Kruskal's Algorithm

A minimum spanning tree (MST) connects every vertex of an undirected, weighted graph using V − 1 edges, with no cycles, and with the smallest possible total weight.

Kruskal's algorithm doesn't grow one tree like Prim's. Instead it looks at the edges from cheapest to most expensive and keeps an edge whenever it connects two pieces that are not yet connected. Many small trees (a forest) slowly merge into one spanning tree.

Take the cheapest edge that doesn't make a cycle. Repeat.

Using the Visualizer

  • • Build your graph: press Edit graph to slide out the matrix and type a weight into any cell. Cell [i][j] is the edge between i and j, and it is copied to [j][i] for you because the graph is undirected. 0 means no edge.
  • • Vertices / Random / Example: inside the drawer, change the size, get a random connected graph, or load the example back. The graph updates while you type.
  • • Colours: vertices with the same colour are in the same set (the same tree of the forest).
  • • The controls above the board: Play / Pause runs the algorithm; Back and Step move one step at a time (or use ← → and space), and the bar under them jumps to any step.
  • • The sorted edge list on the right shows which edge is next, which were kept and which were skipped.
  • • The highlighted pseudocode line tells you exactly which part of the algorithm is running.

How Kruskal's Algorithm Works

1. Sort the edges

Read every edge out of the upper half of the matrix and sort them by weight. Cheap edges get the first chance.

2. Every vertex is its own set

A disjoint-set (union-find) structure remembers which vertices are already connected. At the start, nobody is connected to anybody.

3. Different sets → keep it

If find(u) ≠ find(v) the edge links two separate trees, so it can't close a loop. Add it (green) and union the two sets (the colours merge).

4. Same set → skip it

If both ends are already in the same set there is already a path between them, so the edge would form a cycle (red, crossed out). Stop once V − 1 edges are in.

Prim's vs Kruskal's: both are greedy and both give a minimum spanning tree (the same total weight). Prim's grows one tree from a start vertex and suits dense graphs; Kruskal's works edge by edge, suits sparse graphs, and on a disconnected graph naturally produces a minimum spanning forest.

Implementation

// Kruskal's algorithm on an adjacency matrix (0 = no edge)
// Union-find with path compression and union by rank.
class DisjointSet {
  constructor(n) {
    this.parent = Array.from({ length: n }, (_, i) => i);
    this.rank = Array(n).fill(0);
  }
  find(x) {
    if (this.parent[x] !== x) this.parent[x] = this.find(this.parent[x]);
    return this.parent[x];
  }
  union(a, b) {
    let ra = this.find(a), rb = this.find(b);
    if (ra === rb) return false;           // already in the same tree
    if (this.rank[ra] < this.rank[rb]) [ra, rb] = [rb, ra];
    this.parent[rb] = ra;
    if (this.rank[ra] === this.rank[rb]) this.rank[ra]++;
    return true;
  }
}

function kruskalMST(graph) {
  const n = graph.length;

  // 1. collect every undirected edge once (upper triangle)
  const edges = [];
  for (let i = 0; i < n; i++)
    for (let j = i + 1; j < n; j++)
      if (graph[i][j] !== 0) edges.push([i, j, graph[i][j]]);

  // 2. sort by weight
  edges.sort((a, b) => a[2] - b[2]);

  // 3. take each edge unless it would make a cycle
  const ds = new DisjointSet(n);
  const mst = [];
  let total = 0;
  for (const [u, v, w] of edges) {
    if (ds.union(u, v)) {
      mst.push([u, v, w]);
      total += w;
      if (mst.length === n - 1) break;     // tree is complete
    }
  }
  return { edges: mst, total };
}

// Example
const graph = [
  [0, 7, 0, 5, 0],
  [7, 0, 8, 9, 7],
  [0, 8, 0, 0, 5],
  [5, 9, 0, 0, 15],
  [0, 7, 5, 15, 0],
];
console.log(kruskalMST(graph)); // total: 24

Properties & Complexity

Time Complexity

  • • Sorting edges: O(E log E)
  • • find / union: ≈ O(1) each (inverse Ackermann)
  • • Total: O(E log E) = O(E log V)
  • • Reading a matrix: O(V²) to list the edges

Space & Properties

  • • Space: O(E) edge list + O(V) union-find
  • • Strategy: greedy
  • • Grows: a forest that merges into one tree
  • • Weights: negative weights are fine

Best Use Cases

  • • Sparse graphs: few edges means a cheap sort
  • • Edges given as a list: no need to build an adjacency structure
  • • Network design: cheapest way to wire up every site
  • • Clustering: stop early with k sets to get k clusters

Limitations

  • • Dense graphs: sorting ~V² edges is slower than Prim's O(V²)
  • • Needs union-find: one more data structure to implement
  • • Undirected only: not for directed graphs
  • • Not shortest paths: the MST does not give the shortest route between two vertices
Ad