C Language Algorithm 1.3: Advanced Improved Version of Connectivity Problem (Performance Improvement by 1000 Times) [Video Analysis]

Note: This article is an improved version of the previous article "C Language Algorithm 1.2: Improved Version of Connectivity Problem [Video Analysis]" , it is recommended to read the previous article before reading this article.

! ! ! Friends who like to watch videos, please click here! ! !

1. Source

Program 1.3 from the book "Algorithms: Implementation in C (Parts 1-4) 3rd Edition".


Second, the difference between the two versions

Both versions are implemented using arrays. Suppose there is a one-dimensional array a with a size of 10. The values ​​stored in a[0] to a[9] are 0~9 respectively, that is, the value of each element is different. Same.

version 1.2 version 1.3
implement logic Using a tree structure, when merging, merge the tree on the left under the tree on the right. When using a tree structure, when merging, the tree with a smaller depth is merged under the tree with a larger depth.
Advantages and disadvantages Slow to find, fast to merge Fast search and fast merge

3. Schematic diagram of version 1.3

insert image description here
In the previous version 1.2, the tree on the left was always merged into the tree on the right, resulting in an extremely long tree depth, and a lot of queries were required to find the root node.

However, in the current version 1.3, the small tree is always merged into the large tree to achieve a balanced tree depth, so the number of queries required to find the root node is much less.

4. Performance test results

Number of nodes Time-consuming version 1.2 (milliseconds) Version 1.3 takes time (milliseconds) time-consuming ratio
10000 0 0 neglect
100,000 3199 2 1599
1000000 50522 25 2020
  1. The performance improvement reaches more than 1000 times.
  2. The higher the number of nodes, the higher the performance improvement.

Five, source code

There are many source files, so I won’t post them in the article. The links are here: github , gitee


6. Schematic diagram of the process

insert image description here


end of text

Guess you like

Origin blog.csdn.net/h837087787/article/details/122180163