linear search
Linear Search
Linear search is the simplest search algorithm and often called sequential search. In this type of searching, we simply traverse the list completely and match each element of the list with the item whose location is to be found. If the match found then location of the item is returned otherwise the algorithm return NULL.
Linear search is mostly used to search an unordered list in which the items are not sorted. The algorithm of linear search is given as follows.
Linear Search Algorithm (Sequential Search Algorithm)
Linear search algorithm finds a given element in a list of elements with O(n) time complexity where n is total number of elements in the list. This search process starts comparing search element with the first element in the list. If both are matched then result is element found otherwise search element is compared with the next element in the list. Repeat the same until search element is compared with the last element in the list, if that last element also doesn't match, then the result is "Element not found in the list". That means, the search element is compared with element by element in the list.
Linear search is implemented using following steps...
- Step 1 - Read the search element from the user.
- Step 2 - Compare the search element with the first element in the list.
- Step 3 - If both are matched, then display "Given element is found!!!" and terminate the function
- Step 4 - If both are not matched, then compare search element with the next element in the list.
- Step 5 - Repeat steps 3 and 4 until search element is compared with last element in the list.
- Step 6 - If last element in the list also doesn't match, then display "Element is not found!!!" and terminate the function.
Algorithm
Linear Search ( Array A, Value x) // x = value to be search
Step 1: Set i to 0
Step 2: if i > n-1 then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Complexity of
algorithm
Complexity |
Best Case |
Average Case |
Worst Case |
Time |
O(1) |
O(n) |
O(n) |
Space |
O(1) |
Example
Consider the following list of elements and the element to be searched...