Proofs: Treap split
These are the human proofs of Treap split, at full length.
Treap split returns two treaps that partition the keys full
This proof shows: correctness.
A treap is a binary tree with (P1) the search order on keys and (P2) the max-heap order on priorities. Write for the set of keys of the subtree , and for its set of nodes.
Theorem. Let be a treap or nil and a key. Then SPLIT returns , where and are treaps, , , and . Each node keeps its key and priority.
Proof. By induction on the number of nodes of . If is nil, line L1 returns two empty trees, which is right.
Case (lines L2 to L5). Let and . Since is a treap with fewer nodes, the induction hypothesis gives, at line L3, treaps and with , and .
After line L4, has the left subtree and the right subtree . We check that this tree, , is a treap.
- (P1) at : each key of is less than , since is unchanged. Each key of is a key of , so it is greater than . Inside and , (P1) holds since they are treaps.
- (P2) at : the root of , if any, is a node of , and every node of has priority at most , by (P2) in the old . The left child is unchanged. Inside and , (P2) holds.
Its keys are . Every key of and itself is less than , and is the set of keys of less than . Since , the keys of are exactly the keys of less than . The tree is a treap whose keys are those of that are at least ; the keys of and are less than , so these are all the keys of at least . The nodes of and are .
Case (lines L6 to L9). This is the mirror image: every key of is greater than , so and its right subtree belong in . By induction, line L7 splits into (keys less than ) and (keys at least ). After line L8, has the left subtree and the right subtree . The keys of come from , so they are less than , and their priorities are at most ; so is a treap with the keys of at least , and is a treap with the keys of less than .
Termination and cost. Each call recurses on one child of , so the calls follow one path from the root down, and there are at most of them, where is the height of . Each does work. The visited nodes are the nodes on the search path of : at each node, the call goes right when the key is less than and left otherwise, as a search for would (with a key equal to treated as greater).