3

I am unable to correlate union operation in quick find algorithm with general meaning of A U B in set theory.

Book(Algorithms in C++ Robert Sedgewick) tells union operation is "scanning throgh the whole array for each input pair.(line 9 and 10 in code).

Basically we are copying value at node q to all other nodes having same value as node p. Why do we name this operation as UNION?

Code is directly copied from the book.

#include <iostream>
const int N = 10000;
int main() {
int i, p, q, id[N];
for( i = 0; i < N; i++ ) id[i] = i;
while( cin >> p >> q ) {
    int t = id[p];
    if ( t = id[q] ) continue;              //quick find operation
    for ( i = 0; i < N; i++ )               //---> union why?
        if ( id[i] == t) id[i] = id[q];
    cout << " " << p << " " << q << endl;
}
}
P K
  • 9,972
  • 12
  • 53
  • 99

3 Answers3

2

The union step in quick find means merging the components with the same id. In a general sense it's kinda like the union of two sets. You can consider two sets, onw with id1 as id of all its components and another as id2. For a great explanation look at this presentation in the quick find section:

http://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf

Sid
  • 7,511
  • 2
  • 28
  • 41
1

Look at the set of operations supported. If there is no way to ask "list all the elements", but just insert, find & union, then there is no way to tell, using these operations, whether or not there is duplication of elements. It makes the supported operations more efficient, and still BEHAVES (as far as the user can tell) like a set.

Robert Groves
  • 7,574
  • 6
  • 38
  • 50
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Yes, this is a union operation. Indices are members of the same set if they refer to the same value. The initialization line of code

for( i = 0; i < N; i++ ) id[i] = i;

sets the value of each index to itself, making each index its own set of one member.

(0) (1) (2) (3) (4) (5) (6) (7) (8) (9)...

If you add the edge (1, 2), the union operation will make both of those indices refer to 2, making them members of the same set. If you add the edge (3, 4) those two indices will be unioned by making them both refer to the value 4.

At this point the array would be in this state:

index: 0 1 2 3 4 5 6 7 8 9 ...
value: 0 2 2 4 4 5 6 7 8 9 ...

which represents the sets:

(0) (1, 2) (3, 4) (5) (6) (7) (8) (9)...

Now if we add one more edge (2, 3), what would happen? Any indices with a value of 2 will be set to the value at index 3, unioning those two sets together. The array values will be:

index: 0 1 2 3 4 5 6 7 8 9 ...
value: 0 4 4 4 4 5 6 7 8 9 ...

which represents the sets:

(0) (1, 2, 3, 4) (5) (6) (7) (8) (9)...
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880