Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Union-Find Quick Find

Union-Find Quick Find

This section introduces the basic operations—query, merge, and checking connectivity—based on the Union-Find structure from the previous section.

To query the set number of an element, directly return the id array value,O(1) time complexity.

...

private

int

find

(

int

p

)

{

   

assert

p

=

0

&&

p

<

count

;

   

return

id

[

p

]

;

}

...

To merge the sets to which element p and element q belong, the merge process needs to traverse all elements once, then merge the set numbers of the two elements; this process is O(n) complexity.

...

public

void

unionElements

(

int

p,

int

q

)

{

   

int

pID

=

find

(

p

)

;

   

int

qID

=

find

(

q

)

;

   

if

(

pID

==

qID

)

       

return

;

   

for

(

int

i

=

0

;

i

<

count

;

i

++

)

       

if

(

id

[

i

]

==

pID

)

            id

[

i

]

=

qID

;

}

...

Java Example Code

Source code package download:Download

UnionFind1.java file code:

package

runoob.union

;

/**
 * First version of Union-Find
 */

public

class

UnionFind1

{

   

// Our first version of Union-Find is essentially an array

   

private

int

[

]

id

;

   

// number of data items

   

private

int

count

;

   

public

UnionFind1

(

int

n

)

{

        count

=

n

;

        id

=

new

int

[

n

]

;

       

// initialize; each id[i] points to itself, with no elements merged

       

for

(

int

i

=

0

;

i

<

n

;

i

++

)

            id

[

i

]

=

i

;

   

}

   

// search process: find the set number corresponding to element p

   

private

int

find

(

int

p

)

{

       

assert

p

=

0

&&

p

<

count

;

       

return

id

[

p

]

;

   

}

   

// check whether elements p and q belong to the same set

   

// O(1) complexity

   

public

boolean

isConnected

(

int

p,

int

q

)

{

       

return

find

(

p

)

==

find

(

q

)

;

   

}

   

// merge the sets to which elements p and q belong

   

// O(n) complexity

   

public

void

unionElements

(

int

p,

int

q

)

{

       

int

pID

=

find

(

p

)

;

       

int

qID

=

find

(

q

)

;

       

if

(

pID

==

qID

)

           

return

;

       

// The merge process needs to traverse all elements, merging the set numbers that the two elements belong to

       

for

(

int

i

=

0

;

i

<

count

;

i

++

)

           

if

(

id

[

i

]

==

pID

)

                id

[

i

]

=

qID

;

   

}

}