Proofs: Circular suffix array
These are the human proofs of Circular suffix array, at full length.
Cyclic prefix doubling sorts the rotations of a string full
This proof shows: correctness, termination, time.worst.
Notation. with , and all position arithmetic is modulo . The rotation . For , let be the string of length whose -th symbol is ; it is the prefix of length of the infinite periodic word . The claim is that CYCLIC-SORT returns with in the order that compares the rotation first and the position second.
Lemma 1. For , if and only if , and if and only if .
Proof. . If , the two rotations have the same length , so they first differ at some offset , and and first differ at the same offset with the same two symbols. If , then the two periodic words are equal, so all their prefixes are equal.
Lemma 2 (doubling). . So if and only if the pair is smaller than in the order that compares the first component first.
Proof. The symbol at offset of is , which is the symbol at offset of . Two strings of the same length compare as the pairs of their halves.
Invariant. At each test of line L4 with the current value of :
(D) is a permutation of with , and is the number of distinct strings among that are smaller than . In particular , and if and only if .
Initialization. Before the first test, and . The symbols are mapped to their ranks among the distinct symbols, which is exactly the class of (D), and line L2 sorts the positions by this key.
Maintenance. Assume (D) for , with . Line L5 sets . As goes from 0 to , the position has , so the list is sorted by , the second half of (Lemma 2). It is a permutation, because is a bijection modulo . Line L6 sorts stably by , that is, by the first half. A stable sort by the first key of a list already sorted by the second key gives the list sorted by the pair, so by Lemma 2 the new is sorted by . Line L7 walks through the new . Two neighbors have equal if and only if both halves are equal, which (D) lets us test by the classes, and the new class increases by 1 exactly when the string changes. Since is sorted, the new class of is the number of distinct values below . Line L8 doubles , so (D) holds at the next test.
Termination. takes the values , so the loop stops after rounds, when . Then by (D) and Lemma 1, if and only if , and if and only if . Line L9 sorts the list stably by . The result is sorted by rotation, and equal rotations keep the increasing order of their positions. This is the claim. For , line L1 returns the empty array.
Theorem (time). CYCLIC-SORT takes time after the symbols are mapped to .
Proof. Lines L5 to L8 take time: a counting sort with buckets is , and line L7 makes class comparisons for each . There are rounds. Lines L2 and L9 are counting sorts with at most buckets, since . The mapping of symbols takes time for an integer alphabet of size and comparisons for a general ordered alphabet.