Algorithm Search⌘K

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 vv, each item in the left subtree of vv is less than v.keyv.key, and no item in the right subtree of vv is less than v.keyv.key.

Lemma 1 (insert). If TT is ordered, then after INSERT(T,x)(T, x) the tree is ordered and holds the items of TT and xx.

Proof. INSERT does not change the existing nodes or links; it adds one leaf. Let v0,v1,…,vdv_0, v_1, \ldots, v_d be the nodes on the path from the root, where the new leaf uu becomes a child of vdv_d. At each vjv_j, the walk goes left when x<vj.keyx < v_j.key and right otherwise. So for each jj, uu is in the left subtree of vjv_j exactly when x<vj.keyx < v_j.key, which is the condition for vjv_j. The nodes that are not on the path do not have uu in their subtrees. So each node still meets the condition. □\square

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 rr with subtrees LL and RR, both are ordered, so by the hypothesis the traversal lists LL in order, then rr, then RR in order. Each item of LL is less than r.keyr.key, and no item of RR is less than r.keyr.key. So the full list is non-decreasing. □\square

Theorem 1. After TREE-SORT(A)(A), the array AA holds the items of the input in non-decreasing order.

Proof. The empty tree is ordered. By Lemma 1 and induction on ii, 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 nn items in non-decreasing order and write them into A[0…n−1]A[0 \ldots n-1]. ■\blacksquare

Theorem 2 (stability). If A[i]A[i] and A[j]A[j] have equal keys and i<ji < j, then A[i]A[i] is written before A[j]A[j].

Proof. The node of A[j]A[j] is added after the node of A[i]A[i], as a new leaf, and nodes are never moved. So the node of A[j]A[j] is not an ancestor of the node of A[i]A[i]. There are two cases.

If the node of A[i]A[i] is an ancestor of the node of A[j]A[j], the walk of A[j]A[j] passed it. There A[j]<A[i]A[j] < A[i] is false, because the keys are equal, so the walk went right. So A[j]A[j] is in the right subtree of A[i]A[i], which inorder visits after A[i]A[i].

Otherwise, let ww be the lowest common ancestor of the two nodes; it is a third node, and the two items are in different subtrees of ww. But both walks passed ww, and the test x<w.keyx < w.key 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. ■\blacksquare

Termination. Each insert walks down a path of a finite tree and stops at an empty place, and the traversal visits each of the nn nodes once.

Back to Tree sort