Kruskal's Algorithm in Java
Last Updated :
08 Jul, 2024
Kruskal's Algorithm is the popular algorithm used to find the Minimum Spanning Tree (MST) of the connected, undirected graph. The MST of the graph is the subset of its edges that connects all the vertices together without any cycles and the minimum possible total edge weight. Kruskal's Algorithm is work by sorting of all the edges of a graph in the non-decreasing order of their weights. Then, it repeatedly adds the smallest edge to the MST, provided it doesn't form the cycle with already included edges. The process continues until the V-1 edges in the MST where V is the number of vertices.
What is Kruskal's Algorithm?
Kruskal's Algorithm is a classic algorithm in the graph theory used to find the Minimum Spanning Tree (MST) of a connected, undirected graph. The MST of the graph is a subset of its edges that connects all the vertices together, without any cycles and with the minimum possible total edge weight. This is useful in various applications such as network design, circuit design and other scenarios where we need to minimize the cost of connecting a set of points.
Key Terminologies of Kruskal's Algorithm:
- Graph: A collection of the vertices or nodes and edges that means the connection between vertices.
- Spanning Tree: Subgraph that can include all vertices of the original graph and is a single connected component with no cycles.
- Minimum Spanning Tree (MST): A spanning tree with the minimum possible sum of the edge weights.
Uses of Kruskal's Algorithm:
- Network Design: Designing the least-cost networks like electrical grids, telecommunication networks and computer networks.
- Approximation Algorithms: Used as part of algorithms for various NP-hard problems like approximating the travelling salesman problem.
- Cluster Analysis: In machine learning, MST can help with hierarchical clustering.
Pseudocode for Kruskal's Algorithm:
KRUSKAL(G):
1. A ← ∅ // Initialize A to be empty
2. for each vertex v in G.V:
MAKE-SET(v) // Create a singleton set for each vertex
3. sort the edges of G.E in non-decreasing order by weight w
4. for each edge (u, v) in the sorted order:
if FIND-SET(u) ≠ FIND-SET(v): // If u and v are in different sets
A ← A ∪ {(u, v)} // Add edge (u, v) to the MST
UNION(u, v) // Combine the sets of u and v
5. return A // A is the set of edges in the MST
// Helper Functions:
MAKE-SET(x):
1. parent[x] ← x // Initialize x's parent to itself
2. rank[x] ← 0 // Initialize the rank of x to 0
FIND-SET(x):
1. if x ≠ parent[x]:
parent[x] ← FIND-SET(parent[x]) // Path compression
2. return parent[x]
UNION(x, y):
1. rootX ← FIND-SET(x)
2. rootY ← FIND-SET(y)
3. if rootX ≠ rootY:
if rank[rootX] > rank[rootY]:
parent[rootY] ← rootX
else if rank[rootX] < rank[rootY]:
parent[rootX] ← rootY
else:
parent[rootY] ← rootX
rank[rootX] ← rank[rootX] + 1
Implementation of Kruskal's Algorithm:
Java
// Java Program to Implement
// Krushkal's Algorithm
import java.util.*;
class Edge implements Comparable<Edge> {
int src, dest, weight;
public Edge(int src, int dest, int weight) {
this.src = src;
this.dest = dest;
this.weight = weight;
}
// Compare two edges based on their weight
@Override
public int compareTo(Edge compareEdge) {
return this.weight - compareEdge.weight;
}
}
class Graph {
int V, E; // Number of vertices and edges
Edge[] edges; // Array to store all edges
// Constructor
public Graph(int V, int E) {
this.V = V;
this.E = E;
edges = new Edge[E];
}
// A utility function to find the subset of an element i
int find(int[] parent, int i) {
if (parent[i] == -1)
return i;
return find(parent, parent[i]);
}
// A utility function to do union of two subsets
void union(int[] parent, int x, int y) {
int xset = find(parent, x);
int yset = find(parent, y);
parent[xset] = yset;
}
// Function to perform Kruskal's algorithm to find the MST
void kruskalMST() {
// This will store the resultant MST
Edge[] result = new Edge[V - 1];
int e = 0; // Index variable for result[]
int i = 0; // Index variable for sorted edges
// Sort all the edges in non-decreasing
// order of their weight
Arrays.sort(edges);
// Allocate memory for creating V subsets
int[] parent = new int[V];
Arrays.fill(parent, -1);
// Number of edges to be taken is equal to V-1
while (e < V - 1) {
// Pick the smallest edge. Check if it forms
// a cycle with the MST formed so far
Edge next_edge = edges[i++];
int x = find(parent, next_edge.src);
int y = find(parent, next_edge.dest);
// If including this edge does not cause a cycle, include
// it in the result and increment the index of the result
if (x != y) {
result[e++] = next_edge;
union(parent, x, y);
}
}
// Print the result MST
System.out.println("Edges in the MST:");
for (i = 0; i < e; ++i)
System.out.println(result[i].src + " - "
+ result[i].dest + ": " + result[i].weight);
}
}
public class Main {
public static void main(String[] args) {
int V = 4; // Number of vertices
int E = 5; // Number of edges
Graph graph = new Graph(V, E);
// Add edges
graph.edges[0] = new Edge(0, 1, 10);
graph.edges[1] = new Edge(0, 2, 6);
graph.edges[2] = new Edge(0, 3, 5);
graph.edges[3] = new Edge(1, 3, 15);
graph.edges[4] = new Edge(2, 3, 4);
// Function call to find MST using Kruskal's algorithm
graph.kruskalMST();
}
}
OutputEdges in the MST:
2 - 3: 4
0 - 3: 5
0 - 1: 10
Complexity of the above method:
Time Complexity: O(E log E)
Space Complexity: O(E + V)
Advantages and Disadvantages of Kruskal's Algorithm
Advantage
- Simplicity: Kruskal's Algorithm is the conceptually straightforward and easy understand for the beginners. It is the often more intuitive compared to the other MST algorithms such as the Prim's Algorithm.
- Efficiency on Sparse Graphs: Kruskal's Algorithm is perform well on sparse graphs that means graphs with the relatively few edges compared to number of vertices. The time complexity is mainly dependent on number of edges E.
- Greedy Approach: The algorithm is based on the greedy approach which is ensure that the minimum weight edge is added at the each step leading to the optimal solution.
- Flexibility with Edge Weights: It is handle the graphs with the varying edge weights effectively. The sorting step is ensure that edges are processed in order of the weights and it leads to the optimal MST.
- Parallelism Potential: The sorting step and union-find the operation can be parallelized which can be further speed up algorithm on the modern multi-core processors.
- Handling Disconnected Graphs: Kruskal's Algorithm can adapted to find Minimum Spanning Forest (MSF) for the disconnected graphs where the generate the spanning tree for each connected component.
Disadvantages
- Inefficiency on Dense Graphs: For the dense graphs, Kruskal's Algorithm can less efficient compared to the Prim's Algorithm. The sorting step is become the bottleneck due to O(E log E) time complexity.
- Requires Sorting: The need to sort the all edges initially can be a drawback for the very large graphs, especially when number of edges is significantly greater than number of vertices.
- Union-Find Data Structure Complexity: Implementing the union-find data structure with the path compression and union by the rank can complex and may require additional understanding and coding effort.
- Not Suitable for All Types of Graphs: Kruskal's Algorithm is primarily designed for the undirected graphs. Although it can be adapted, it is not suited for the directed graphs.
- Memory Usage: In addition to the storing the graphs, the algorithm needs to the extra memory for union-find structure, which might be the concern for the large graphs.
Applications of Kruskal's Algorithm
- Network Design: Design the efficient and cost-effective network infrastructures such as computer networks, telecommunication networks or transportation networks.
- Urban Planning: Planning road networks, work supply systems or electrical grids in the new urban area.
- Cluster Analysis: Grouping similar data points in machine learning and data mining.
- Circuit Design: Designing the layout of the electrical circuits on the chip to minimize the total length of the interconnections.
- Transportation Networks: Creating the minimal-cost route map for the city's public transport system.
- Telecommunications: Establishing the network of communication towers to provide the maximum coverage with the minimum total connection cost.
- Game Development: Creating the navigation mesh for AI characters in the game environment.
- Geographical Information Systems (GIS): Analyzing and optimizing the routes or connections between the geographical locations.
- Network Reliability: Enhancing reliability of the network by minimizing risk of the failure.
Similar Reads
Kruskal's Algorithm in Python Kruskalâs Algorithm is a greedy algorithm used to find MST in the graph. A minimum spanning tree (MST) is a spanning tree with a weight less than or equal to the weight of every other spanning tree. Kruskalâs Algorithm sorts all edges of the given graph in increasing order. Then it keeps on adding n
4 min read
Kahnâs Algorithm in C++ In this post, we will see the implementation of Kahnâs Algorithm in C++.What is Kahnâs Algorithm?Kahnâs Algorithm is a classic algorithm used for topological sorting of a directed acyclic graph (DAG). Topological sorting is a linear ordering of vertices such that for every directed edge u -> v, v
4 min read
Kosarajuâs Algorithm in C Kosarajuâs Algorithm is a method by which we can use to find all strongly connected components (SCCs) in a directed graph. This algorithm has application in various applications such as finding cycles in a graph, understanding the structure of the web, and analyzing networks.In this article, we will
5 min read
Kahnâs Algorithm in C Language In this post, we will see the implementation of Kahn's Algorithm in C language.What is Kahn's Algorithm?The Kahn's Algorithm is a classic algorithm used to the perform the topological sorting on the Directed Acyclic Graph (DAG). It produces a linear ordering of the vertices such that for every direc
5 min read
Kahn's Algorithm in Python Kahn's Algorithm is used for topological sorting of a directed acyclic graph (DAG). The algorithm works by repeatedly removing nodes with no incoming edges and recording them in a topological order. Here's a step-by-step implementation of Kahn's Algorithm in Python. Example: Input:Â V=6 , E = {{2, 3}
4 min read
Johnson Algorithm in C Johnson's Algorithm is an efficient algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. It works even for graphs with negative weights, provided there are no negative weight cycles. This algorithm is particularly useful for sparse graphs and combines both Dij
5 min read
Johnson Algorithm in C++ Johnsonâs Algorithm is an algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. It is especially useful for sparse graphs and can handle negative weights, provided there are no negative weight cycles. This algorithm uses both Bellman-Ford and Dijkstra's algorit
8 min read
Prim's Algorithm with a Java Implementation Prim's Algorithm is a popular Algorithm in the field of computer science and Graph Theory It is used to find the Minimum Spanning Tree of a weighted, undirected graph. The Minimum Spanning Tree is the subset of the Graph that connects all vertices with minimum total edge weight that is also without
5 min read
Java Program to Implement Bellman Ford Algorithm The Bellman-Ford algorithm is an essential method in graph theory and algorithms used to determine the shortest paths in a weighted graph from one vertex of origin to all other vertexes. This article will cover implementing the Bellman-Ford algorithm in Java language and also explore its intricacies
6 min read
Boruvka's Algorithm using Python Boruvka's algorithm is a greedy algorithm for finding the Minimum Spanning Tree (MST) in a connected, weighted, and undirected graph. It was one of the first algorithms for this problem and is named after Otakar Borůvka, who introduced it in 1926. This algorithm works by repeatedly finding the short
10 min read