Algorithm Search⌘K

Proofs: Linear search

These are the human proofs of Linear search, at full length.

Linear search returns the first index of x, or NIL when x is not in A full

This proof shows: correctness, termination.

Let A[0…n−1]A[0 \ldots n-1] be an array with n≥0n \ge 0 and let xx be a key. We prove that LINEAR-SEARCH(A,x)(A, x) stops, and that it returns the smallest index ii with A[i]=xA[i] = x, or NIL when there is no such index.

Invariant. Before the pass of the loop of line L1 with index ii, and also when the loop ends with i=ni = n, this statement holds:

P(i):0≤i≤n and A[j]≠x for each j with 0≤j<i.P(i): \quad 0 \le i \le n \text{ and } A[j] \ne x \text{ for each } j \text{ with } 0 \le j < i.

Start. The first pass has i=0i = 0. The range 0≤j<00 \le j < 0 is empty, and 0≤n0 \le n, so P(0)P(0) holds. If n=0n = 0 the loop does no pass, and P(0)P(0) is the statement at the end.

Step. Assume P(i)P(i) and that the pass with index ii runs, so i≤n−1i \le n - 1. Line L2 tests A[i]=xA[i] = x. If the test is true, the algorithm returns and the loop has no next pass. If the test is false, then A[i]≠xA[i] \ne x. With P(i)P(i), A[j]≠xA[j] \ne x for each j<i+1j < i + 1, and i+1≤ni + 1 \le n. So P(i+1)P(i + 1) holds before the next pass, or at the end of the loop when i+1=ni + 1 = n.

Termination. The index ii starts at 0 and grows by exactly 1 in each pass that does not return. The loop has no pass with i≥ni \ge n. So it runs at most nn passes, and the algorithm stops after at most nn key tests.

Result. There are two ways to stop.

  1. Line L2 returns ii. Then 0≤i≤n−10 \le i \le n - 1 and A[i]=xA[i] = x, so ii is an index of xx. By P(i)P(i), no index j<ij < i has A[j]=xA[j] = x. So ii is the smallest index of xx.
  2. Line L3 returns NIL. The loop ended after the pass with i=n−1i = n - 1 or, when n=0n = 0, without a pass. In both cases P(n)P(n) holds: A[j]≠xA[j] \ne x for each jj with 0≤j<n0 \le j < n. So xx is not in AA and NIL is correct.

■\blacksquare

The number of tests. If xx first occurs at index ii, the algorithm makes exactly i+1i + 1 key tests: the passes 0,…,i−10, \ldots, i - 1 fail by the minimality of ii, and the pass ii succeeds. If xx is absent, it makes exactly nn key tests. These counts give the best, worst and average cases on the page.

Back to Linear search