0% found this document useful (0 votes)
9 views3 pages

Implementing Kruskal's Algorithm

KruskalAlgorithm

Uploaded by

Padmanabh Bhole
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views3 pages

Implementing Kruskal's Algorithm

KruskalAlgorithm

Uploaded by

Padmanabh Bhole
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import [Link].

Scanner;

class Edge {
int src, dest, weight;

public Edge(int src, int dest, int weight) {


[Link] = src;
[Link] = dest;
[Link] = weight;
}
}

class KruskalAlgorithm {
private int V; Number of vertices
private int E; Number of edges
private Edge[] edges; Array of edges
private int edgeCount = 0;

public KruskalAlgorithm(int v, int edgeCount) {


V = v;
E = edgeCount;
edges = new Edge[edgeCount];
}

public void addEdge(int src, int dest, int weight) {


edges[edgeCount++] = new Edge(src, dest, weight);
}

private int findParent(int[] parent, int vertex) {


if (parent[vertex] != vertex) {
parent[vertex] = findParent(parent, parent[vertex]); Path compression
}
return parent[vertex];
}

private void union(int[] parent, int[] rank, int x, int y) {


int rootX = findParent(parent, x);
int rootY = findParent(parent, y);

if (rootX != rootY) {
if (rank[rootX] rank[rootY]) {
parent[rootX] = rootY;
} else if (rank[rootX] rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}

private void sortEdges() {


for (int i = 0; i E; i++) {
for (int j = 0; j E - i - 1; j++) {
if (edges[j].weight edges[j + 1].weight) {
Edge temp = edges[j];
edges[j] = edges[j + 1];
edges[j + 1] = temp;
}
}
}
}

public void KruskalsMST() {


sortEdges();

int[] parent = new int[V];


int[] rank = new int[V];

for (int i = 0; i V; i++) {


parent[i] = i;
rank[i] = 0;
}

Edge[] MST = new Edge[V - 1];


int mstIndex = 0;
int mstWeight = 0;

for (int i = 0; i E; i++) {


if (mstIndex == V - 1) break;

Edge edge = edges[i];


int srcParent = findParent(parent, [Link]);
int destParent = findParent(parent, [Link]);

if (srcParent != destParent) {
MST[mstIndex++] = edge;
mstWeight += [Link];
union(parent, rank, srcParent, destParent);
}
}

[Link](Edges in the MST);


[Link](SrctDesttWeight);
for (int i = 0; i mstIndex; i++) {
[Link](MST[i].src + -- + MST[i].dest + == +
MST[i].weight);
}
[Link](Total weight of MST + mstWeight);
}
}

public class MinSpanTree {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link](Enter number of vertices );


int V = [Link]();

[Link](Enter number of edges );


int E = [Link]();

KruskalAlgorithm graph = new KruskalAlgorithm(V, E);

[Link](Enter edges in the format src dest weight);


for (int i = 0; i E; i++) {
int src = [Link]();
int dest = [Link]();
int weight = [Link]();
[Link](src, dest, weight);
}

[Link]();

[Link]();
}
}

Common questions

Powered by AI

The KruskalAlgorithm class utilizes an Edge array to store information about the graph's edges. Edges are added using the addEdge method, which constructs a new Edge object with specific source, destination, and weight parameters, then stores it in the edges array at the current edgeCount index, subsequently incrementing edgeCount to keep track of the number of edges added.

The KruskalAlgorithm ensures that a valid MST is generated without cycles by using the union-find data structure to keep track of connected components. When considering each edge, it checks whether adding the edge would create a cycle by determining if both vertices of the edge belong to the same component. If they do not, the edge is added to the MST and the components are unified. This process prevents cycles while ensuring that all vertices are connected.

The parent array in KruskalAlgorithm tracks the leader or representative of each vertex's set, while the rank array maintains the depth of the trees representing the disjoint sets. Using these arrays together optimizes the performance of the union-find operations by ensuring path compression and union by rank, which dramatically reduces the time complexity of these operations and thus accelerates the process of cycle detection and creation of the MST.

The findParent method uses path compression to optimize the process of finding the representative parent of a given vertex, which flattens the structure of the tree whenever findParent is called by pointing nodes directly to the root node. The union method employs union by rank to keep the tree as flat as possible by attaching the smaller tree under the larger tree, which minimizes the tree height and thereby reduces the time complexity of future find operations.

The KruskalAlgorithm is particularly suitable for solving the MST problem in sparse graphs due to its edge-centric approach, focusing on the global edge selection process rather than vertex expansion. This algorithm efficiently finds the MST by initially considering all edges and incrementally building the MST using only edges that do not induce cycles, facilitated by union-find data structures that quickly manage the connected components. This method is optimal for graphs where the number of edges is relatively low compared to the vertices.

Bubble sort is generally inefficient for sorting in the KruskalAlgorithm because it has a time complexity of O(E^2), making it impractical for large numbers of edges. Given the algorithm's dependency on sorting to function properly, using a faster, comparison-based sorting algorithm like quicksort or mergesort would significantly boost the efficiency, reducing the sorting time to O(E log E) and thus improving overall performance in finding the MST.

Sorting the edges in non-decreasing order is essential for Kruskal's algorithm as it ensures that the edges are processed in order of their weights. This ordering is crucial for maintaining the greedy nature of the algorithm, which makes a locally optimal choice (i.e., choosing the smallest available edge) at each step. By ensuring that the lightest edges are considered first, the algorithm constructs an MST with the minimal possible total weight.

The KruskalAlgorithm utilizes a simple bubble sort algorithm to organize the edges in non-decreasing order based on their weights. This is done through nested loops where each edge is compared with the next one, and they are swapped if they are out of order, effectively bubbling up the largest element to the end of the array with each iteration.

The performance of KruskalAlgorithm can be significantly hindered in the case of dense graphs where the number of edges approaches O(V^2). In such scenarios, the time complexity driven by sorting all the edges can become a bottleneck, making the algorithm less efficient compared to Prim's algorithm, which is more vertex-focused and can handle edge-intensive situations more effectively.

The Scanner class in the MinSpanTree's main method facilitates input collection by allowing the user to input the number of vertices, number of edges, and details of each edge such as source, destination, and weight. Using Scanner ensures that user inputs can be conveniently read directly from the console, providing a straightforward mechanism to interact with the KruskalAlgorithm in real-time and test its operation efficiently.

You might also like