Original: Step by step write algorithm (Kruskal algorithm)
"Disclaimer: Copyright, welcome reprint, please do not use for commercial purposes. Contact mailbox: feixiaoxing @163.com "
Before discussing the algorithm of Kruskal, we analyzed the basic process of the algorithm, the basic data structure and the three problems that need to be solved in the algorithm (sorting, judging, merging). Today, we continue to complete the rest of the content. In the merge function, we call two basic functions,Find_tree_by_index and Delete_mini_tree_from_group, and the detailed calculation process is given below.
mini_generate_tree* Find_tree_by_index (mini_generate_tree* ptree[], int length, int point) {int Outer;int inner;for ( outer = 0; Outer < length; outer++) {for (inner = 0; inner < ptree[outer]->node_num; inner + +) {if (point = = Ptree[outer]->pnode[inner]) return ptree[outer];}} return NULL;} void Delete_mini_tree_from_group (mini_generate_tree* ptree[], int length, mini_generate_tree* pindex) {int index;for ( index = 0; Index < length; Index + +) {if (Pindex = = Ptree[index]) break;} Memmove (&ptree[index +1], &ptree[index], sizeof (mini_generate_tree*) * (Length-1-index); return;}
Here you can start writing the Kruskal minimum spanning tree, as shown in the code below.
mini_generate_tree* _kruskal (mini_generate_tree* ptree[], int length, dir_line* pline[], int number) {int index;if (NULL = = PTree | | NULL = = PLine) return null;for (index = 0; index < number; index + +) {Bubble_sort (void**) pLine, number, compare, swap); if (2 = = Isdoublevectexexistintree (pTree, Length, Pline[index]->start, pline[index]->end)) continue; Mergetwominigeneratetree (pTree, Length, Pline[index]->start, Pline[index]->end, pline[index]->weight); Length--;} return (1! = length)? NULL:PTREE[0];}
To do the above calculation, we also need to figure out the number of vertices, the number of segments, so the function needs to be further refined and supplemented,
mini_generate_tree* Kruskal (graph* pgraph) {mini_generate_tree** ptree;dir_line** pline;int count;int number;if (NULL = = pgraph) Return null;count = Pgraph->count;number = Get_total_line_number (pgraph);p tree = Get_tree_from_graph ( pgraph);p line = Get_line_from_graph (pgraph); return _kruskal (PTree, Count, PLine, number);}
In this way, the Kruskal algorithm is largely over, where Get_total_line_number, Get_tree_from_graph, get_line_from_graph functions are relatively simple, friends can continue to complete their own, but to test well.
Summarize:
(1) The code does not consider the memory release problem, need to improve and improve
(2) Part of the code can be reused in the prim algorithm content, data structure is the same
(3) The algorithm is written in your understanding, as long as the steps to, coupled with testing, the general problem is not very
Step-by-step write algorithm (Kruskal algorithm)