Graphs · O(E log E)

Kruskal's minimum spanning tree

Sort edges by weight and keep each one unless union-find says it would close a cycle.

The full explanation, derivation and practice are in the lesson Minimum spanning trees: cut and cycle properties, Kruskal and Prim.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

namespace Bekadan.Dsa.Examples.Graphs;
 
/// <summary>Accepted edge indices (in acceptance order), total weight, number of trees in the forest and edges examined.</summary>
public sealed record SpanningForest(List<int> Edges, long TotalWeight, int Components, int Examined);
 
/// <summary>
/// Kruskal's minimum spanning tree on an undirected graph (WeightedEdge lists each
/// edge once). Edges are scanned by (weight, input index); the UnionFind class
/// (union by rank, path compression) rejects an edge whose endpoints are already
/// connected, because it would close a cycle. Stops once n - 1 edges are chosen.
/// A disconnected graph yields a minimum spanning forest. O(E log E) for the sort,
/// O(E α(V)) for the union-find work. Negative weights are fine.
/// </summary>
public static class Kruskal
{
    public static SpanningForest Run(int nodeCount, IReadOnlyList<WeightedEdge> edges)
    {
        var sets = new UnionFind(nodeCount);
        var tree = new List<int>();
        long total = 0;
        int examined = 0;
 
        int[] order = Enumerable.Range(0, edges.Count).ToArray();
        Array.Sort(order, (a, b) => edges[a].Weight != edges[b].Weight ? edges[a].Weight.CompareTo(edges[b].Weight) : a.CompareTo(b));
 
        foreach (int i in order)
        {
            if (tree.Count == nodeCount - 1)
                break; // a spanning tree has exactly n - 1 edges
            var e = edges[i];
            examined++;
            int ru = sets.Find(e.From);
            int rv = sets.Find(e.To);
            if (ru == rv)
                continue; // already connected: this edge would close a cycle
            sets.Union(e.From, e.To);
            tree.Add(i);
            total += e.Weight;
        }
        return new SpanningForest(tree, total, sets.Count, examined);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Graphs/Kruskal.cs

"""Kruskal's minimum spanning tree on an undirected graph (each edge listed once).
 
Edges are scanned by (weight, input index); UnionFind (union by rank, path
compression) rejects an edge whose endpoints are already connected, because it
would close a cycle. The scan stops once n - 1 edges are chosen. A disconnected
graph yields a minimum spanning forest. O(E log E) for the sort, O(E * alpha(V))
for the union-find work. Negative weights are fine.
"""
 
from dataclasses import dataclass
 
from dsa_examples.union_find import UnionFind
 
 
@dataclass
class SpanningForest:
    edges: list[int]  # accepted edge indices, in acceptance order
    total_weight: int
    components: int
    examined: int
 
 
def kruskal(node_count: int, edges: list[tuple[int, int, int]]) -> SpanningForest:
    sets = UnionFind(node_count)
    tree: list[int] = []
    total = 0
    examined = 0
 
    order = sorted(range(len(edges)), key=lambda i: (edges[i][2], i))
 
    for i in order:
        if len(tree) == node_count - 1:
            break  # a spanning tree has exactly n - 1 edges
        u, v, weight = edges[i]
        examined += 1
        ru, rv = sets.find(u), sets.find(v)
        if ru == rv:
            continue  # already connected: this edge would close a cycle
        sets.union(u, v)
        tree.append(i)
        total += weight
    return SpanningForest(tree, total, sets.count, examined)

Tested on CPython 3.14.0 · examples/python/dsa_examples/kruskal.py

package dev.bekadan.dsa.graphs;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
/**
 * Kruskal's minimum spanning tree on an undirected graph (each edge listed once). Edges are
 * scanned by (weight, input index); {@link UnionFind} (union by rank, path compression) rejects
 * an edge whose endpoints are already connected, because it would close a cycle. The scan stops
 * once n - 1 edges are chosen. A disconnected graph yields a minimum spanning forest.
 * O(E log E) for the sort, O(E α(V)) for the union-find work. Negative weights are fine.
 */
public final class Kruskal {
    private Kruskal() {
    }
 
    public record Edge(int from, int to, int weight) {
    }
 
    /** Accepted edge indices in acceptance order, total weight, trees in the forest, edges examined. */
    public record Result(List<Integer> edges, long totalWeight, int components, int examined) {
    }
 
    public static Result run(int nodeCount, List<Edge> edges) {
        UnionFind sets = new UnionFind(nodeCount);
        List<Integer> tree = new ArrayList<>();
        long total = 0;
        int examined = 0;
 
        Integer[] order = new Integer[edges.size()];
        Arrays.setAll(order, i -> i);
        Arrays.sort(order, (a, b) -> edges.get(a).weight() != edges.get(b).weight()
                ? Integer.compare(edges.get(a).weight(), edges.get(b).weight())
                : Integer.compare(a, b));
 
        for (int i : order) {
            if (tree.size() == nodeCount - 1) {
                break; // a spanning tree has exactly n - 1 edges
            }
            Edge e = edges.get(i);
            examined++;
            int ru = sets.find(e.from());
            int rv = sets.find(e.to());
            if (ru == rv) {
                continue; // already connected: this edge would close a cycle
            }
            sets.union(e.from(), e.to());
            tree.add(i);
            total += e.weight();
        }
        return new Result(tree, total, sets.count(), examined);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/graphs/Kruskal.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <numeric>
#include <vector>
 
#include "bekadan/dsa/union_find.hpp"
 
namespace bekadan::dsa {
 
struct UndirectedEdge {
    std::size_t from;
    std::size_t to;
    int weight;
};
 
struct SpanningForest {
    std::vector<std::size_t> edges;  // accepted edge indices, in acceptance order
    long long total_weight = 0;
    std::size_t components = 0;
    std::size_t examined = 0;
};
 
// Kruskal's minimum spanning tree on an undirected graph (each edge listed once). Edges are
// scanned by (weight, input index); UnionFind (union by rank, path compression) rejects an edge
// whose endpoints are already connected, because it would close a cycle. The scan stops once
// n - 1 edges are chosen. A disconnected graph yields a minimum spanning forest.
// O(E log E) for the sort, O(E α(V)) for the union-find work. Negative weights are fine.
inline SpanningForest kruskal(std::size_t node_count, const std::vector<UndirectedEdge>& edges) {
    UnionFind sets(node_count);
    SpanningForest result;
 
    std::vector<std::size_t> order(edges.size());
    std::iota(order.begin(), order.end(), std::size_t{0});
    std::ranges::sort(order, [&edges](std::size_t a, std::size_t b) {
        return edges[a].weight != edges[b].weight ? edges[a].weight < edges[b].weight : a < b;
    });
 
    for (const std::size_t i : order) {
        if (result.edges.size() + 1 == node_count) break;  // a spanning tree has exactly n - 1 edges
        const UndirectedEdge& e = edges[i];
        ++result.examined;
        const std::size_t ru = sets.find(e.from);
        const std::size_t rv = sets.find(e.to);
        if (ru == rv) continue;  // already connected: this edge would close a cycle
        sets.unite(e.from, e.to);
        result.edges.push_back(i);
        result.total_weight += e.weight;
    }
    result.components = sets.count();
    return result;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/kruskal.hpp