# Linear search

This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages)
(Learn how and when to remove this template message) |

Class | Search algorithm |
---|---|

Worst-case performance | O(n) |

Best-case performance | O(1) |

Average performance | O(n) |

Worst-case space complexity | O(1) iterative |

In computer science, a **linear search** or **sequential search** is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched.^{[1]}

A linear search runs in at worst linear time and makes at most *n* comparisons, where *n* is the length of the list. If each element is equally likely to be searched, then linear search has an average case of *n*/2 comparisons, but the average case can be affected if the search probabilities for each element vary. Linear search is rarely practical because other search algorithms and schemes, such as the binary search algorithm and hash tables, allow significantly faster searching for all but short lists.^{[2]}

## Contents

## Algorithm[edit]

A linear search sequentially checks each element of the list until it finds an element that matches the target value. If the algorithm reaches the end of the list, the search terminates unsuccessfully.^{[1]}

### Basic algorithm[edit]

Given a list *L* of *n* elements with values or records *L*_{0} .... *L*_{n−1}, and target value *T*, the following subroutine uses linear search to find the index of the target *T* in *L*.^{[3]}

- Set
*i*to 0. - If
*L*_{i}=*T*, the search terminates successfully; return*i*. - Increase
*i*by 1. - If
*i*<*n*, go to step 2. Otherwise, the search terminates unsuccessfully.

### With a sentinel[edit]

The basic algorithm above makes two comparisons per iteration: one to check if *L*_{i} equals *t*, and the other to check if *i* still points to a valid index of the list. By adding an extra record *L*_{n} to the list (a sentinel value) that equals the target, the second comparison can be eliminated until the end of the search, making the algorithm faster. The search will reach the sentinel if the target is not contained within the list.^{[4]}

- Set
*i*to 0. - If
*L*_{i}=*T*, go to step 4. - Increase
*i*by 1 and go to step 2. - If
*i*<*n*, the search terminates successfully; return*i*. Else, the search terminates unsuccessfully.

### In an ordered table[edit]

If the list is ordered such that *L*_{0} ≤ *L*_{1} ... ≤ *L*_{n−1}, the search can establish the absence of the target more quickly by concluding the search once *L*_{i} exceeds the target. This variation requires a sentinel that is greater than the target.^{[5]}

- Set
*i*to 0. - If
*L*_{i}≥*T*, go to step 4. - Increase
*i*by 1 and go to step 2. - If
*L*_{i}=*T*, the search terminates successfully; return*i*. Else, the search terminates unsuccessfully.

## Implementations in Different Programming Languages[edit]

### C[edit]

```
1 #include<stdio.h>
2 void main()
3 {
4 int a[] = {31,72,65,85,56};
5 int n = sizeof(a)/sizeof(int);
6 int i, e = 65, pos =- 1;
7 printf("Array:");
8 for (i=0;i<n;i++)
9 {
10 printf(" %d", a[i]);
11 }
12 for (i=0;i<n;i++)
13 {
14 if(a[i] == e)
15 {
16 pos=i;
17 break;
18 }
19 }
20 if (pos >= 0)
21 printf("\nElement at %d", pos);
22 else
23 printf("\nElement not in array");
24 }
```

### Java[edit]

```
1 class LinearSearch()
2 {
3 public static void main(String atgs[])
4 {
5 int a[] = {31, 72, 65, 85, 56};
6 int n = 5;
7
8 System.out.println("Array:");
9 for(int i = 0; i < n; i++)
10 {
11 System.out.print(a[0] + " ");
12 }
13
14 int ele = 65;
15 int pos = -1;
16 for(int i = 0; i < n; i++)
17 {
18 if(a[i] == ele)
19 {
20 pos=i;
21 break;
22 }
23 }
24
25 if(pos!=-1)
26 System.out.println("Element at position " + pos);
27 else
28 System.out.println("Element not in array");
29 }
30 }
```

### Python3[edit]

```
1 arr = [2,3,4,10,40]
2 ele, n, pos = 10, len(arr), -1
3 print("Array:", end=" ")
4 for i in range(0,n):
5 print(arr[i], end=" ")
6 for i in range(0,n):
7 if(arr[i] == ele):
8 pos = i
9 break
10 if(pos == -1):
11 print("Element is not present in array")
12 else:
13 print("Element is present at index", pos)
```

## Analysis[edit]

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

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 . However, if it is *known* that it occurs once, then at most *n* - 1 comparisons are needed, and the expected number of comparisons is

(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[edit]

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). ^{[6]}

## Application[edit]

Linear search is usually very simple to implement, and is practical when the list has only a few elements, or when performing a single search in an un-ordered list.

When many values have to be searched in the same list, it often pays to pre-process the list in order to use a faster method. For example, one may sort the list and use binary search, or build an efficient search data structure from it. Should the content of the list change frequently, repeated re-organization may be more trouble than it is worth.

As a result, even though in theory other search algorithms may be faster than linear search (for instance binary search), in practice even on medium-sized arrays (around 100 items or less) it might be infeasible to use anything else. On larger arrays, it only makes sense to use other, faster search methods if the data is large enough, because the initial time to prepare (sort) the data is comparable to many linear searches ^{[7]}

## See also[edit]

## References[edit]

### Citations[edit]

- ^
^{a}^{b}Knuth 1998, §6.1 ("Sequential search"). **^**Knuth 1998, §6.2 ("Searching by Comparison Of Keys").**^**Knuth 1998, §6.1 ("Sequential search"), subsection "Algorithm B".**^**Knuth 1998, §6.1 ("Sequential search"), subsection "Algorithm Q".**^**Knuth 1998, §6.1 ("Sequential search"), subsection "Algorithm T".**^**Knuth, Donald (1997). "Section 6.1: Sequential Searching,".*Sorting and Searching*; the Art of Computer Programming.**3**(3rd ed.). Addison-Wesley. pp. 396–408. ISBN 0-201-89685-0.**^**Horvath, Adam. "Binary search and linear search performance on the .NET and Mono platform". Retrieved 19 April 2013.

### Works[edit]

- Knuth, Donald (1998).
*Sorting and Searching*. The Art of Computer Programming.**3**(2nd ed.). Reading, MA: Addison-Wesley Professional. ISBN 0-201-89685-0