Java code to implement Kruskal's algorithm
Kruskal algorithm
Kruskal algorithm is a greedy algorithm used to solve the minimum spanning tree problem. A minimum spanning tree is a spanning tree with the smallest sum of edge weights in a connected undirected graph. Kruskal's algorithm selects edges in order from small to large edge weights. When the selected edges do not form a cycle, they are added to the spanning tree. The specific implementation process is as follows:
Sort all edges according to their edge weights from small to large.
Select edges in turn. If the two endpoints of the selected edge are not in the same connected component, add this edge to the minimum spanning tree and merge the two endpoints into the same connected component.
Until the minimum spanning tree contains all the vertices in the graph.
The advantage of the algorithm is that it only needs to pay attention to the weight of the edge and has nothing to do with the degree of the vertex, so it can also show better performance in dense graphs. At the same time, Kruskal's algorithm also has good scalability and can easily handle the minimum spanning forest problem in weighted graphs.
Execution process
Sort all the edges according to their weights from small to large;
Traverse each edge in turn, If the two nodes connected by this edge are not in the same connected component, add this edge to the spanning tree and merge the two nodes into one connected component;
Repeat Step 2 Until all nodes are in the same connected component, the tree generated at this time is the minimum spanning tree.
During the implementation process, union-find sets are usually used to maintain connectivity to improve efficiency.
Code implementation
import java.util.*; public class KruskalAlgorithm { // 定义边的数据结构 class Edge implements Comparable<Edge> { int src, dest, weight; public int compareTo(Edge edge) { return this.weight - edge.weight; } } // 并查集数据结构 class Subset { int parent, rank; } int V, E; // V是顶点数,E是边数 Edge edge[]; // 存储边的数组 // 构造函数,初始化边和顶点数 KruskalAlgorithm(int v, int e) { V = v; E = e; edge = new Edge[E]; for (int i = 0; i < e; ++i) edge[i] = new Edge(); } // 查找父节点 int find(Subset subsets[], int i) { if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent; } // 合并两个子集 void union(Subset subsets[], int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; else { subsets[yroot].parent = xroot; subsets[xroot].rank++; } } // 执行克鲁斯卡尔算法 void kruskal() { Edge result[] = new Edge[V]; // 存储结果的数组 int e = 0; // 表示result数组中的下标 // 将边按照权重从小到大排序 Arrays.sort(edge); // 创建V个子集 Subset subsets[] = new Subset[V]; for (int i = 0; i < V; ++i) subsets[i] = new Subset(); // 初始化每个子集的父节点和秩 for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } // 取E-1条边 int i = 0; while (e < V - 1) { Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); // 如果两个节点不在同一个集合中,合并它们 if (x != y) { result[e++] = next_edge; union(subsets, x, y); } } // 打印结果 System.out.println("Following are the edges in the constructed MST"); for (i = 0; i < e; ++i){ System.out.println(result[i].src + " - " + result[i" - " + result[i].weight); return; } // 定义一个辅助函数,用于查找结点所在的集合 private int find(int parent[], int i) { if (parent[i] == -1) return i; return find(parent, parent[i]); } // 定义一个辅助函数,用于合并两个集合 private void union(int parent[], int x, int y) { int xset = find(parent, x); int yset = find(parent, y); parent[xset] = yset; } } }
The function uses the sort method of the Arrays class to sort the edges according to their weight from small to large. Then, the function traverses the sorted edges in sequence, and for each edge, uses the find function to find the root node of the set where its src and dest are located. If the root nodes are different, it means that the two sets are not connected and can be merged, and the edges are added to the result array of the minimum spanning tree. Finally, the function traverses the result array of the minimum spanning tree and outputs the starting point, end point and weight of each edge.
In this implementation, a method of quickly searching for sets is used, that is, using union search to achieve it. Each node has a parent array, where parent[i] represents the parent node of node i. If parent[i] == -1, node i is the root node. When searching for the set where the node is located, if the parent node of the current node is -1, it means that the node is the root node and is returned directly; otherwise, the set where the parent node is located is searched recursively. When merging two collections, find the root nodes of the two collections to be merged, and set the parent node of one root node to the index of the other root node, that is, merge the root node of one collection under the root node of the other collection. .
The time complexity of Kruskal's algorithm implemented in this way is O(ElogE), where E represents the number of edges in the graph. The main time cost lies in the process of sorting the edges. The space complexity is O(V E), where V represents the number of vertices in the graph. The main space overhead is to store the edges and parent arrays.
The above is the detailed content of Java code to implement Kruskal's algorithm. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.
