1

I found a tutorial that created the makes and finds methods as such

public void makeSet(long data) {
        Node node = new Node();
        node.data = data;
        node.parent = node;
        node.rank = 0;
        map.put(data, node);
    }

private Node findSet(Node node) {
        Node parent = node.parent;
        if (parent == node) {
            return parent;
        }
        node.parent = findSet(node.parent);
        return node.parent;
    }

Here is the link to the full code to Here is the link to the Kruskal Algorithm

I'm confused on why they are returning a node who's parent is itself instead of the different node and what the rank is used for when implementing Union when the rank is set to 0. I've tried finding other Kruskal Algorithm code and explanations but there are very few sources that go over the implementation.

Keyur
  • 180
  • 1
  • 5
  • 20

1 Answers1

0

Kruskal's algorithm works like this:

  1. Put each node is in its own subtree
  2. Sort edges by their weight
  3. Find first node that connects two nodes that are in different subtrees
  4. Join subtrees that the edge connects
  5. Repeat steps 3 and 4 until there are no more edges to test or the tree is complete

In this particular implementation, each node can be in one of two states:

  1. It's subtree's "master" node (if node.parent == node)
  2. Is's a non-master not and has a link to another node in the same subtree (if node.parent != node)

When you test whether an edge connects two separate subtrees, you compare the master of the first node to the master of 2nd node. If they are equal, then the nodes are in the same subtree and you can ignore the edge.

If the master of 1st node is not equal to the master of 2nd node, you join those subtrees: set the parent of "master of 2nd node" to the master of 1st node.

When you end up with a single master node that has (node.parent == node) then you have a full tree. Of course, it's easier to simply count the edges, as you expect N-1 edges for a tree.

user3429660
  • 2,420
  • 4
  • 25
  • 41