1. Introduction

In this tutorial, we’ll show how to minimize the number of comparisons in linear search.

2. Number of Comparisons

Let’s say we have an array a with n elements and a value x. Our goal is to check if the value is in the array and, in doing so, make the least possible number of comparisons. Here, we count all comparisons, even those involving auxiliary variables in loops.

Although minimizing the number of comparisons may not be very useful in everyday applications, there are use cases where each optimization counts. For instance, code running in embedded systems with restricted memory needs to use resources optimally, so it makes sense to try low-level optimization hacks in such scenarios.

We assume that a isn’t sorted and that indexing starts from 1.

Usually, we run the linear search to solve this problem. It’s an O(n) brute-force algorithm:

We can reduce the number of comparisons by appending \boldsymbol{x} to \boldsymbol{a}. That way, we modify the original array. If n is the number of elements before appending x, the appended element is a[n+1], and we make sure that a[n+1] = x is true.

As a result, we don’t need to check if \boldsymbol{i} is within the original array’s bounds (\boldsymbol{1 \leq i \leq n}). If x isn’t in a[1:n], a[n+1] = x ensures we exit the loop after i becomes greater than n, so checking i is unnecessary: