Graph Theory37 sections · 1633 units
Open in Course

Implementation - Union by Size

Coding the Merger

Here is the implementation:

function unite(i, j):
    rootA = find(i)
    rootB = find(j)
    if rootA != rootB:
        if size[rootA] < size[rootB]:
            swap(rootA, rootB)
        parent[rootB] = rootA
        size[rootA] = size[rootA] + size[rootB]

This runs in O(α(n))O(\alpha(n)) amortized time and uses O(n)O(n) space.