Algorithm Search⌘K

Proofs: Quick Search algorithm

These are the human proofs of Quick Search algorithm, at full length.

Quick Search outputs exactly the valid shifts full

This proof shows: correctness, termination.

Claim. For a text T[0…n−1]T[0 \ldots n-1] and a pattern P[0…m−1]P[0 \ldots m-1], QUICK-SEARCH(T,P)(T, P) stops and outputs exactly the shifts ss, 0≤s≤n−m0 \le s \le n - m, with T[s…s+m−1]=PT[s \ldots s+m-1] = P, in increasing order.

For m=0m = 0, line L2 outputs every shift, which is correct. Let m≥1m \ge 1. Since line L4 visits kk in increasing order, the last write for cc is its largest kk, so after line L4

qs[c]=min⁡({m+1}∪{ m−k:0≤k≤m−1, P[k]=c }),1≤qs[c]≤m+1.\mathrm{qs}[c] = \min\big(\{m + 1\} \cup \{\, m - k : 0 \le k \le m - 1,\ P[k] = c \,\}\big), \quad 1 \le \mathrm{qs}[c] \le m + 1.

Lemma (safe shift). Let s<n−ms < n - m and c=T[s+m]c = T[s + m]. No shift s′s' with s<s′<s+qs[c]s < s' < s + \mathrm{qs}[c] and s′≤n−ms' \le n - m is valid.

Proof. Let s′=s+ds' = s + d with 1≤d<qs[c]1 \le d < \mathrm{qs}[c], so d≤md \le m. The text position s+ms + m lies in the window at s′s' and faces the pattern position k=m−dk = m - d, with 0≤k≤m−10 \le k \le m - 1. If s′s' were valid, then P[k]=cP[k] = c, so m−k=dm - k = d is in the set defining qs[c]\mathrm{qs}[c], and qs[c]≤d\mathrm{qs}[c] \le d, a contradiction. □\square

Theorem. The claim holds.

Proof. Invariant at line L6: the output is the increasing list of the valid shifts smaller than ss. It holds for s=0s = 0. In an iteration with s≤n−ms \le n - m, lines L7 and L8 end with j=mj = m exactly when the window equals PP, so line L9 outputs ss exactly when it is valid, after all smaller ones. If s=n−ms = n - m, line L10 stops, and every valid shift, being at most n−m=sn - m = s, has been output. Otherwise s+m<ns + m < n, line L11 reads an existing character, and by the lemma no valid shift lies strictly between ss and the new ss, so the invariant holds. Each iteration increases ss by at least 1, so the loop ends after at most n−m+1n - m + 1 iterations, either at line L10 or with s>n−ms > n - m; in both cases all valid shifts have been output. ■\blacksquare

Back to Quick Search algorithm