Proofs: Tree sort
These are the human proofs of Tree sort, at full length.
Tree sort writes a sorted permutation of the input, stably full
This proof shows: correctness.
We call a binary tree whose nodes hold items ordered when for each node , each item in the left subtree of is less than , and no item in the right subtree of is less than .
Lemma 1 (insert). If is ordered, then after INSERT the tree is ordered and holds the items of and .
Proof. INSERT does not change the existing nodes or links; it adds one leaf. Let be the nodes on the path from the root, where the new leaf becomes a child of . At each , the walk goes left when and right otherwise. So for each , is in the left subtree of exactly when , which is the condition for . The nodes that are not on the path do not have in their subtrees. So each node still meets the condition.
Lemma 2 (inorder). The inorder traversal of an ordered tree lists its items in non-decreasing order.
Proof. By induction on the number of nodes. The empty tree gives an empty list. For a root with subtrees and , both are ordered, so by the hypothesis the traversal lists in order, then , then in order. Each item of is less than , and no item of is less than . So the full list is non-decreasing.
Theorem 1. After TREE-SORT, the array holds the items of the input in non-decreasing order.
Proof. The empty tree is ordered. By Lemma 1 and induction on , after the loop of lines L2 and L3 the tree is ordered and holds each item of the input once. By Lemma 2, lines L5 and L6 visit its items in non-decreasing order and write them into .
Theorem 2 (stability). If and have equal keys and , then is written before .
Proof. The node of is added after the node of , as a new leaf, and nodes are never moved. So the node of is not an ancestor of the node of . There are two cases.
If the node of is an ancestor of the node of , the walk of passed it. There is false, because the keys are equal, so the walk went right. So is in the right subtree of , which inorder visits after .
Otherwise, let be the lowest common ancestor of the two nodes; it is a third node, and the two items are in different subtrees of . But both walks passed , and the test has the same result for two items with equal keys, so both went to the same side. This is a contradiction, so this case does not occur.
Termination. Each insert walks down a path of a finite tree and stops at an empty place, and the traversal visits each of the nodes once.