Common search algorithm (a): sequential search

Linear search or a sequential search is a find a particular value of the search algorithm , refers to certain order check array each element, up to a certain value until it finds to be looking. It is the simplest kind of search algorithm .

Assuming that there is an array of n elements, the best situation is to find a particular value is the first element of the array, so only need 1 comparisons can be. The worst case scenario is a specific value or not in this array is the last element in the array are looking for, which requires n times compared.

When the search is successful the average search length :( assuming equal probability of each data element) ASL = 1 / n (1 + 2 + 3 + ... + n) = (n + 1) / 2 

The time complexity is O (the n-) , the best case is the first one to find, is O (1), the worst is not found, is O (n).

1 //顺序查找
2 int SequenceSearch(int a[], int value, int n)
3 {
4     int i;
5     for(i=0; i<n; i++)
6         if(a[i]==value)
7             return i;
8     return -1;
9 }

 

Guess you like

Origin www.cnblogs.com/magic-sea/p/11374282.html