Linear Search Algorithm is a very basic yet important search algorithm that you should know. Though it is not implemented in complex searches involving huge data, still it is often the best way to learn searching algorithms as after implementing this, you can proceed to more complex algorithms like binary search, jump search etc. So lets get started.
Linear search basically involves iterating through items in an array from the leftmost element. When a match is found, the current index is returned. If there’s no match, then -1 is returned.
We can take the inputs of the array and the item to be searched from the user and then perform the iteration using loop. For ease of development, the best approach is to make a function for searching where we perform the search and then return the result to the main function. This will be clear when we see the implementation. First, lets figure out the algorithm.
Algorithm
Steps:
- Set the values and store it in an array.
- Get the value that need to be searched.
- Iterate through all the values using loop.
- If match is found, return the index, else return -1.
Implementation using C programming language
Now, let us implement this algorithm by writing a program. I am using C language since it is a common beginner’s language but you can also use any other programming language. So here it goes:
#include <stdio.h>
int linearSearch(int arr[], int n)
{
int i;
for(i=0;i<n;i++)
{
if(arr[i]==n)
{
return i;
}
}
return -1;
}
int main()
{
int arr[5],n,result;
printf("Enter 5 elements:\n");
for(int i=0;i<5;i++)
{
scanf("%d",&arr[i]);
}
printf("Enter the element to be searched:\n");
scanf("%d",&n);
result=linearSearch(arr,n);
printf("Returned index:%d",result);
return 0;
}
Outputs


Program Explanation
We created a linearSearch function where we have written the logic for iterating the array, which it receives as a parameter. It also receives the value to be searched as a parameter. In the main function, we are creating an array of size 5 and taking input from the user to fill those five. Then we are taking input for the item that need to be searched and storing it in the variable n;
Finally, we are calling the linearSearch function and passing the array and n as parameters and assigning the result of the function call in the variable result.
In the final step, we are displaying the returned index.
Wrapping Up
Well, in this way you can simply implement the linear search algorithm. Though you can also use some modifications in the program considering time complexity and other factors, but this post is just to show the basic implementation without taking into account complex factors. I hope that this post helped you. Thanks for reading!
Also Read: Why Java is platform independent?