For a list with
n items, the best case is when the value is equal to the first element of the list, in which case only one comparison is needed. The worst case is when the value is not in the list (or occurs only once at the end of the list), in which case
n comparisons are needed. If the value being sought occurs
k times in the list, and all orderings of the list are equally likely, the expected number of comparisons is : \begin{cases} n & \mbox{if } k = 0 \\[5pt] \displaystyle\frac{n + 1}{k + 1} & \mbox{if } 1 \le k \le n. \end{cases} For example, if the value being sought occurs once in the list, and all orderings of the list are equally likely, the expected number of comparisons is \frac{n + 1}2. However, if it is
known that it occurs once, then at most
n − 1 comparisons are needed, and the expected number of comparisons is :\displaystyle\frac{(n + 2)(n-1)}{2n} (for example, for
n = 2 this is 1, corresponding to a single if-then-else construct). Either way,
asymptotically the worst-case cost and the expected cost of linear search are both
O(
n).
Non-uniform probabilities The performance of linear search improves if the desired value is more likely to be near the beginning of the list than to its end. Therefore, if some values are much more likely to be searched than others, it is desirable to place them at the beginning of the list. In particular, when the list items are arranged in order of decreasing probability, and these probabilities are
geometrically distributed, the cost of linear search is only O(1). In general, if items are arranged in order of decreasing probability and the probability of searching for the
ith element is p_i, the expected cost of a single search is ES^{OPT} = \sum_{i=1}^n ip_i. Under the natural assumption that the probabilities are not known in advance, or one cannot spend the time to sort the list by probabilities, one can use the approach of
self-adjusting data structure and move elements towards the head of the list when they are requested in a search. Two natural heuristics for this self-adjustment are
Move to Front (MF) and
Transpose (T), where the requested element trades places with its predecessor. It is known that the expected cost of an access in a large sequence of independent accesses, averaged over all initial orders of the list, satisfies ES^T \le ES^{MF} \le \frac{\pi}{2}ES^{OPT}. In terms of
amortized cost, averaging over a worst-case sequence of operations (note - among sequences satisfying the assumption on probabilities), we have S^{MF}\le 2S^{OPT}, while S^T can be as bad as O(mS^{OPT}). ==Application==