Proofs: Merge sort tree
These are the human proofs of Merge sort tree, at full length.
The merge sort tree answers counting and k-th queries correctly full
This proof shows: correctness, complexity.
Let be an array over a totally ordered set, the least power of two with , and number the nodes as in the page: node has the children and , and the leaf is position . Node at depth covers , where and .
Lemma 1 (build). After BUILD, each is the sorted list of the multiset .
Proof. By induction on from down to . A leaf holds if (line L7) and the empty list otherwise, which is sorted. For , is the disjoint union of and , so , and the merge of two sorted lists (line L8) is the sorted list of the union of their multisets.
Lemma 2 (canonical nodes). For , the nodes at which lines L3 and L4 call LOWER have pairwise disjoint ranges whose union is , and there are at most two of them per level.
Proof. Write for the variables after line L1. We keep the invariant: the nodes used so far cover minus the union of for , where ranges over the nodes of the current level, and the used nodes are disjoint from . At the start nothing is used and is the union of the leaves , which is . In one round, if is odd, node is the right child of its parent, so the node is moved from to the used set and becomes even; the same holds for odd with . Now and are even, so the nodes pair up into the children of , and line L5 keeps the same. The loop stops when , so is empty, and each round uses at most two nodes of one level.
Theorem 1 (count). COUNT returns .
Proof. By Lemma 2 the positions of with are split among the used nodes, each in exactly one, and by Lemma 1 LOWER is the number of those positions with . Summing gives the claim. The same proof with an upper-bound search gives the count of .
Theorem 2 (k-th). For , KTH returns the -th smallest item of .
Proof. Let ; it is non-decreasing in . Let be the -th smallest item of the range. Then , and for every . The root list is sorted (Lemma 1), so it contains , and the predicate is monotone in and true at the last index , since . Lines L9 to L12 are a binary search for the least with , kept by the invariant that holds and fails for all . At the least such , since fails below , and since occurs in at some index where holds. So .
Theorem 3 (cost). BUILD takes time and the lists have items. COUNT takes time and KTH takes .
Proof. The lists of one level hold each of the items once, so the merges of one level take time, and there are levels. By Lemma 2 COUNT does at most binary searches on lists of at most items, each. KTH does rounds of the outer search, each one count. Termination: COUNT halves at least every round, so it runs at most rounds, and the outer search halves .