Public classKruskal { Public Static voidMain (string[] args) {//two-dimensional arrays store the beginning and end points and weights of the edges, respectively int[][]edges = {0,1,6},{0,2,1},{0,3,5},{1,2,5},{1,4,3},{2,3,5},{2,4,6},{2,5,4},{3,5,2},{4,5,6}}; int[]connect = {0,1,2,3,4,5};//auxiliary arrays are used to store two vertices that are not connected initially are not connectedQuick_sort (edges,0,edges.length-1);//sort the edges for(inti=0;i<edges.length;i++){ intV1 = edges[i][0];//the beginning of the side intv2 = edges[i][1];//the end of the edge intVC1 = Connect[v1];//connected state of the starting point intVC2 = Connect[v2];//connected state of the end point if(VC1! = VC2) {//If two points are not connected to the minimum spanning tree and the connected state is changed to the same stateSystem.out.println ((v1+1) + "+" + (v2+1)); for(intj=0;j<connect.length;j++){ if(Connect[j] = =vc2) Connect[j]=VC1; } } } } Public Static voidQuick_sort (intA[][],intLowintHigh ) { if(Low <High ) { intK =sort (a,low,high); Quick_sort (A,low,k-1); Quick_sort (A,k+1, high); } } Public Static intSortintA[][],intLowintHigh ) { int[] k =A[low]; while(low<High ) { while(Low ]) high--; A[low]=A[high]; while(Low ]) Low++; A[high]=A[low]; } A[low]=K; returnLow ; }}
Kruskal algorithm of minimum spanning tree