Proofs: Quick-union
These are the human proofs of Quick-union, at full length.
Quick-union keeps a forest whose trees are the sets full
This proof shows: correctness, termination.
Let the elements be to , and let be the equivalence closure of the pairs of the unions done so far, as in the dynamic equivalence problem. Call a root when . We prove that after each operation:
(U1) For each , the sequence reaches a root within steps. Write for that root.
(U2) For all : if and only if .
(U3) The counter equals the number of roots.
Initialization. After lines L1 and L2, every element is a root, so (U1) holds with 0 steps and . No union has been done, so is equality, and (U2) holds. There are roots and the counter is .
Find. Assume (U1). FIND follows the same sequence as in (U1): the loop of lines L3 and L4 replaces by its parent while is not a root. By (U1) it reaches a root after at most steps, so it stops, and line L5 returns . It writes nothing, so (U1) to (U3) still hold. By (U2), connected(p, q) returns true exactly when .
Union. Assume (U1) to (U3) before UNION. Line L6 sets and , by the find case.
Case . By (U2), , so the new relation equals . Line L7 returns, nothing changes, and the invariants hold.
Case . Line L8 sets , the only change to the array. Let and before the union.
(U1). Take any . If , the path from to its root does not pass through , since a path that reaches ends at , a root. So none of its parents changed, and the path is the same as before. If , the old path from ends at with no repeated node; its nodes are distinct, because a repeated node would make a cycle that never reaches a root. Now it continues from to and then along the old path from to , which is empty because is a root. So the new path from is the old path followed by one edge to , and is still a root. The nodes of this path are distinct: the old path lies in , and , which does not meet . A path of distinct nodes has at most edges. So (U1) holds, with for and otherwise.
(U2). By (U2) before the union, is the class of and the class of under . The relation adds the pair , and its classes are those of with and replaced by : this set is one class because , and no chain of pairs leaves it, since each pair of stays inside one old class and the new pair joins and . The new roots are on and the old roots elsewhere, so equal roots mean one class of .
(U3). The element is no longer a root and no other element changes, so the number of roots falls by one, and line L9 lowers the counter by one.
Conclusion. By induction on the number of operations, (U1) to (U3) hold after each operation. Each find stops and returns a representative that is the same for exactly the elements of one class, which is what the disjoint-set type requires.