Sorting Edges by Weight — Kruskal and Greedy Graphs
In graph algorithms like Kruskal’s MST, edges are processed lightest first. That means you sort edges by weight (often with tie-breakers on endpoints) before a union–find loop tries to add them without forming cycles.
Why this shows up in the real world
A fiber network planner might have thousands of possible cable segments, each with installation cost. Sorting by cost ensures you try cheap redundant links before expensive ones when building a reliable backbone. Logistics sometimes ranks truck routes by fuel estimates before a greedy packing of deliveries. Game AI can rank moves by a heuristic score and explore promising branches first. Sorting is not an end—it is a precondition so greedy choices align with global objectives.
Core idea (explained for students)
Collect edges as tuples (weight, u, v) (or objects). Sort ascending so the greedy routine sees best local connectors first. Tie-break (u, v) lexicographically to make behavior deterministic—important for debugging and for proofs that assume unique ordering. After sorting, the rest of the algorithm is often O(E α(V)) with union–find; sorting dominates at O(E log E).
Try this in Python
edges = [(4, 0, 1), (2, 1, 2), (2, 0, 2), (7, 2, 3)]
edges.sort() # weight, then u, then v by Python tuple order
print(edges)
Common mistakes
- Sorting only weights but forgetting parallel edges or multigraph quirks.
- Integer overflow when summing weights during comparison—use Python big ints or mod policy.
- Non-deterministic ordering when weights tie and endpoints differ—break ties explicitly.
Key takeaways
- Sorting edges is the first act of many MST / matroid greedy proofs.
- Deterministic tie-breaking simplifies tests and reasoning.
- Remember Kruskal needs disjoint sets; sorting alone does not build the tree.
