The next algorithm we consider is a fast merging algorithm that complements the fast lookup algorithm. It is based on the same data structure-an array indexed by the object name-but because its interpretation of element values differs from the fast lookup algorithm, it leads to a more complex abstract structure. In a loop-free structure, each object has a connection to another object in the same collection. To determine whether two objects are in the same set, we walk along the lines of each object, knowing that we have reached an object that has a connection to itself. Two objects in the same set, when and only if their end point is the same object. If two objects are not in the same collection, follow their lines and the end point will not be the same object. So, to implement a merge operation, we just need to connect one collection to another, which is the origin of the quick merge.
Public class quickfind{ public static void main (String[] args) { int n=integer.parseint (args [0]); int id[]=new int[N]; for (int i=0;i<n;i++) id[i]=i; for (In.init ();! In.empty ();) { int i,j,p=in.getint (), Q=in.get (); for (I=p;i!=id[i];i=id[i]); for (J=q;j!=id[j];j=id[j]) if (I==J) &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp; { system.out.println ("P" is connected to Q!) "); continue; } id[i]=j; } }}
The above procedure is the implementation of merging and finding operations in a fast merging algorithm to solve the connectivity problem. Because the fast merge algorithm does not scan the entire array compared to every pair of inputs, it seems to run faster than the fast lookup algorithm. Currently, because it takes out the main disadvantage of the fast lookup algorithm, we can think of the fast merging algorithm as an improvement of the fast lookup algorithm.
This distinction between fast merge and Quick Find algorithms certainly represents a progression, but one drawback of the fast merge algorithm is that we cannot guarantee that it will be much faster in any case than the fast lookup algorithm because the input data may slow down the lookup operation.
This article is from the "Flying Fish Technology" blog, please be sure to keep this source http://flyingfish.blog.51cto.com/9580339/1622553
A fast merging algorithm for the 2--connectivity problem of Java algorithm