Proofs: Quick-find
These are the human proofs of Quick-find, at full length.
Quick-find keeps one name per set and answers each query correctly full
This proof shows: correctness, termination.
Let the elements be to . For a sequence of operations, let be the equivalence closure of the pairs of the unions done so far, as in the dynamic equivalence problem. We prove that after each operation:
(Q) For all : if and only if . Each value is an element with and . The counter equals the number of classes of .
Termination. Each operation runs at most one loop of steps, so it stops.
Initialization. After lines L1 and L2, for each , and no union has been done, so is equality. Then if and only if , each is its own name, and there are classes. So (Q) holds.
Find and connected. These change nothing, so (Q) still holds. By (Q), connected(p, q) returns true exactly when , and find(p) returns an element equivalent to that is the same for all members of the class of .
Union. Assume (Q) before UNION. Let be the relation before and the relation after, the closure of and the pair . Let and be the values that line L4 saves, and let and . By (Q), is the class of and is the class of .
Case . Then by (Q), so . Line L5 returns with no change, and (Q) holds.
Case . Then and are two different classes, and has the classes of except that and are replaced by . Indeed, is closed under : an element -related to a member of is linked to it by a chain of pairs of and the pair , and each such step stays inside or inside a class of that meets , which is or . And all of is one class of , since . The other classes do not meet , and they stay classes of .
The loop of lines L6 and L7 compares each with the saved value , which the loop does not change. Loop invariant: before the step with index , each with an old value now has the value , and every other entry has its old value. It holds for . The step with index writes to entry exactly when its value is , and the value at is still the old one, because only earlier entries have changed. So the invariant holds for . At the end, : the entries of have the value , and all other entries are unchanged.
After the loop, the elements with value are , and for each other old value the elements with value are the same class as before. So equal values mean one class of , which is the first part of (Q). The name is in , and was true before and is not changed, since . The names of the other classes do not change. Two classes merge into one, so the number of classes falls by one, and line L8 lowers the counter by one. So (Q) holds after the union.
Conclusion. By induction on the number of operations, (Q) holds after each operation, so each connected and find answers as the disjoint-set type requires, and the counter is the number of sets.