Linear search is also known as the sequential search. Linear Search is a very simple searching technique in which an array of elements is taken and then a particular element is searched in the array whether it is present or not. When the searching is done for the element, the searching takes place from the very first element of the array. The searched element is checked with each element of the array. If the element is matched with any one element of the array then the index of the found element is printed and if the element is not matched then a message is shown that the element is not present in the array. This searching technique is mostly used to search an unordered list of elements.
EXAMPLE:
Let the array elements are:
Suppose the element which is to be searched is: 12
Now we will start at index 0. first, the element is compared with the first element ‘65’.
As it is not matched, the index will be incremented by 1. Now the index is 1 and the element to be searched will be again compared with that element of the array, which is ‘87’ here.
This is also not matched, again the index will be incremented by 1, making the index value 2. Now the searched element will be compared with the next element ‘12’.
As it is matched, the index ‘2’ will be printed and checking will be stopped.
If the searching element is 89 (let), then it will be compared with all the elements of the array but as it is not present in the array, after comparison with all the elements “Element not found”- this message will be printed.
INPUT: An array element and the element to be searched
OUTPUT: the index of the element if found
PROCESS:
Step 1: [taking the inputs]
Read n [number of elements]
For i=0 to n-1 repeat
Read a[i]
[end of ‘for’ loop]
Read x [the element which is to be searched]
Step 2: [searching the element]
For i=0 to n-1 repeat
If a[i]=x then
break
[End of ‘for’ loop]
If i=n then
print "Element not found"
else
print "Element x is found at position i”
[End of ‘if’]
Step 3: Stop.
ADVANTAGES:
1. The searching is fast for small or medium lists.
2. It is not needed to sort the elements of the list.
3. The searching is not get affected if any element is inserted or deleted.
DISADVANTAGES:
1. The searching process is slow for a large array. If the element is present at the last or near to the last index, then we have to compare the searched element with all the previous elements which will be longer for a large array.
TIME COMPLEXITY:
for(i=0;i<n;i++)-------------------------------------- O(n)
{ if(a[i]==x)--------------------- O(c)
break;
}
The complexity of the linear search is: O(n*c) where c is a constant.
Therefore, the complexity is O(n).
Related