Skip to content

Add Krushkal's Minimum Spanning Tree algorithm #6409

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add Krushkal's Minimum Spanning Tree algorithm
  • Loading branch information
PayalB24 committed Jul 18, 2025
commit a0461b691e2f3c3a4c6e2e407e118a41e1ddd579
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.thealgorithms.graph;
import java.util.*;

/**
* Implements Kruskal's Algorithm to find the Minimum Spanning Tree (MST)
* of a connected, undirected, weighted graph using Union-Find.
*/
public class KruskalMinimumSpanningTree {

static class Edge implements Comparable<Edge> {
int src, dest, weight;

Edge(int src, int dest, int weight) {
this.src = src;
this.dest = dest;
this.weight = weight;
}

@Override
public int compareTo(Edge other) {
return Integer.compare(this.weight, other.weight);
}
}

static class UnionFind {
int[] parent;

UnionFind(int size) {
parent = new int[size];
Arrays.fill(parent, -1);
}

int find(int node) {
if (parent[node] < 0) return node;
return parent[node] = find(parent[node]);
}

boolean union(int u, int v) {
int rootU = find(u);
int rootV = find(v);
if (rootU == rootV) return false;
parent[rootV] = rootU;
return true;
}
}

public static List<Edge> kruskalMST(List<Edge> edges, int vertices) {
Collections.sort(edges);
UnionFind uf = new UnionFind(vertices);
List<Edge> mst = new ArrayList<>();

for (Edge edge : edges) {
if (uf.union(edge.src, edge.dest)) {
mst.add(edge);
}
if (mst.size() == vertices - 1) break;
}

return mst;
}

public static void main(String[] args) {
int V = 4;
List<Edge> edges = new ArrayList<>();
edges.add(new Edge(0, 1, 10));
edges.add(new Edge(0, 2, 6));
edges.add(new Edge(0, 3, 5));
edges.add(new Edge(1, 3, 15));
edges.add(new Edge(2, 3, 4));

List<Edge> mst = kruskalMST(edges, V);
System.out.println("Edges in the Minimum Spanning Tree:");
for (Edge edge : mst) {
System.out.println(edge.src + " - " + edge.dest + " : " + edge.weight);
}
}
}
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy