union method

void union(
  1. T element1,
  2. T element2
)

Unions the sets containing the two given elements

Implements union by rank for optimal performance. If either element doesn't exist, this operation has no effect.

Implementation

void union(T element1, T element2) {
  final root1 = find(element1);
  final root2 = find(element2);

  if (root1 == null || root2 == null || root1 == root2) {
    return; // Elements don't exist or are already in the same set
  }

  final node1 = _nodes[root1]!;
  final node2 = _nodes[root2]!;

  // Union by rank: attach smaller tree to larger tree
  if (node1.rank < node2.rank) {
    node1.parent = node2;
  } else if (node1.rank > node2.rank) {
    node2.parent = node1;
  } else {
    // Same rank, attach one to the other and increment rank
    node2.parent = node1;
    node1.rank++;
  }

  _setCount--;
}