Question

I've been looking into algorithms using a class on coursera. In one of the first lectures, Quick Union Weighted is being discussed. I get what it does and I've tested it out using their code and written a small test for it.

Everything is clear but one point: when you create a union of two objects, it will add the object with the smallest tree to the bigger one. At the same time, the size of the larger tree will be incremented with the size of the smaller tree in a separate array which is used to determine what tree is bigger. Since the array is initiated with value 1 for every index (every node on its own basically is a tree of 1 object), why isn't the value of this index set to 0 instead of remaining on 1?

In order to illustrate this:

// Quick Union Weighted
ID: 0 1 2 3 4 5 6 7 8 9 
SZ: 1 1 1 1 1 1 1 1 1 1 

quw.union(2, 4);
ID: 0 1 2 3 2 5 6 7 8 9 
SZ: 1 1 2 1 1 1 1 1 1 1 

quw.union(5, 4);
ID: 0 1 2 3 2 2 6 7 8 9 
SZ: 1 1 3 1 1 1 1 1 1 1 

quw.union(2, 7);
ID: 0 1 2 3 2 2 6 2 8 9 
SZ: 1 1 4 1 1 1 1 1 1 1 

// Whereas I would've expected to end up with this 
// to point out that the index is empty. 
SZ: 1 1 4 1 0 0 1 0 1 1

Why are the sizes of merged indices 1 instead of 0? You can find the code to test it out here. Note that the implementation is the same as the example provided by the lecturers, which is why I'm assuming my code is correct.

Was it helpful?

Solution

I think this is because the node itself is also size 1 and does not have any children. It can however have children. I'm actually not familiar with Quick-Union Weighted but if it's bit like the other union find algoritmes I've seen you can for example do

quw.union(0, 1);
ID: 0 0 2 3 2 2 6 2 8 9 
SZ: 1 1 4 1 1 1 1 1 1 1

quw.union(0, 2);
ID: 2 2 2 3 2 2 6 2 8 9 
SZ: 2 1 6 1 1 1 1 1 1 1

So now 0 en 1 have merged and the entire tree starting from 0 is merged with 2 again, still making the subtree starting at 0 size 2.

Like I said, I'm not sure it that's possible in Quick-Union Weighted but the reason for the '1' is still because it's also size 1 on its own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top