Proofs: Strand sort
These are the human proofs of Strand sort, at full length.
Strand sort returns the items in sorted order, and it is stable full
This proof shows: correctness.
We write for the list at the start of round of the loop of line L2, for the strand of round , and for after round , with empty and the input.
Lemma 1 (one round). is non-decreasing. Each item of goes to exactly one of and , and each of the two lists keeps the order of .
Proof. Line L3 puts in . The loop of line L4 visits each other item once, in order, and appends it to the end of (line L5) or of (line L6). An item goes to only when it is not less than the last item of , so stays non-decreasing.
Lemma 2 (MERGE). For two sorted lists and , MERGE returns a sorted list of the items of and . It keeps the order of the items of , and of the items of , and on a tie it puts the item of first.
This is the merge of the merging-sorted-lists page, with the rule to take the front item of unless the front item of is smaller.
Theorem 1. STRAND-SORT stops and returns the items of in sorted order.
Proof. Invariant: before round , is sorted, and and together hold the items of the input. It holds for . If it holds before round , then by Lemma 1, is sorted and and together hold the items of ; by Lemma 2, is sorted and holds the items of and . So the invariant holds before round . Each round moves into , so , and the loop stops after at most rounds, with empty. Then is sorted and holds all the items.
Theorem 2 (stability). If and have equal keys and comes before in the input, then comes before in the output.
Proof. Let be in strand and in strand .
First, . Suppose . In round , both and are in , and by Lemma 1 the earlier rounds kept the input order, so comes before in . So is not , because goes to . The scan visits before and sends to , so at that moment . The last item of never decreases during the scan, and has the key of , so when is visited, and goes to too. This contradicts .
If , then is before in by Lemma 1, and the merges keep the order of the items of each input list (Lemma 2), so stays before .
If , then is in when is merged. By Lemma 2, on equal keys the item of comes first, and any item between them in is also kept in order. So comes before in , and the later merges keep the order of the items of .
The number of strands. Let be the number of rounds. Two items of a strictly decreasing subsequence of the input cannot be in the same strand: they keep their order in , and a strand is non-decreasing. So is at least the length of each strictly decreasing subsequence. Conversely, for each item of was in and went to , so it was visited after an item of with , and comes before in the input. Starting from an item of and following these items back to gives items, each earlier in the input and larger than the next. So the longest strictly decreasing subsequence has length exactly .