Assignment #9

A. In this assignment we will implement class DisjointSet with the following (perhaps incomplete) declaration:
class DisjointSet
{
private:
int *S;//Array
int *save;//Could be used in FindCompressed… not necessary
unsigned int Size;
public:
// Constructor
DisjointSet(unsigned int N=100);
// Destructor
~DisjointSet();
// Member functions
void Union( int x,int y);
void UnionBySize( int x,int y);
void UnionByHeight( int x,int y);
boolFind( int x,int y); // returns true if x & y in same sets
intFind( int x); // returns index of root of x
bool FindCompress( int x,int y); // returns true if x & y in same sets
};

B. To test this class, implement a test driver something like this:

#include <conio.h>

#include <iostream.h>
int main()

{
unsigned int x[] = {1, 3, 3, 1, 3, 8, 1,3,3,3,3,14,16,14,1,1}; // This is Exer.
unsigned int y[] = {2, 4, 5, 7, 6, 9, 8, 10, 11, 12, 13,15,0, 16,3, 14};//8.1 data
int NSIZE = 16;
DisjointSet djs(17);
for (i= 0; i< NSIZE; i++)
djs.Union(x[i], y[i]);
for (i= 0; i<=16; i++){
for(j= i+1; j <=16; j++)
if(djs.Find(i, j))
cout << "{" << i << "," << j << "} equivalent" << endl;
else
cout << "{" << i << "," << j << "} Not equivalent" << endl;
cout <<"Press any key to continue"<< endl;
while (!kbhit()); // not ver C++ like, but will pause the screen
getch ();//till you touch a key
}
for (int k = 0; k<=16 ;k++)
cout << djs.Find (k) << ' ';
cout << endl;
return 0;
}

C. After being sure it works, use it to time N unions of random integer pairs from a file integerPairs.zip that I will put in our download area. Do it for Union, Union by size, and UnionByHeight.

 I have found that this runs so fast that timing may not be very meaningful. So instead,  implement functions int numberDisjointSets() and double averagrNodeDepth() and report these instead of timings.



Notes:

1. Conventions: The universe of set elements is 0,1...Size-1. Consequently, s[0] is used, and the sentinel used to mark roots must not be 0; use a negative integer instead. For calculation of average node depth, assume root nodes have a depth of 0.

2 This is not the same as the author’s disjoint set implementation. For one thing, the author’s union function requires that the arguments be roots of trees, whereas the arguments in the union functions defined above are not necessarily roots. Also, the Find( int x,int y) and FindCompress( int x,int y) functions above return booleans.

The author’s single-argument Find(x) function is the same as ours in that it returns an integer which is the root of the tree containing x. However, he implements it recursively. I want you to do a non-recursive implementation. It is very easy to do and is more efficient.