Summary: In this tutorial, we will learn what Linear Search Algorithm is, how Linear Search works, and how to search an element in an array using Linear Search algorithm in C and Java.
Introduction to Linear Search Algorithm
Linear Search sequentially checks each element in an array until the match is found or the whole array has been traversed.
The algorithm compares the search element with every element of the array from start to end in a linear fashion.
Here is how the linear search works:
In this example, the search element is 5. The algorithm matches 5 with every element of the array until a match is found or the array ends.
Linear Search Algorithm
Steps to search in an array using Linear Search Algorithm:
- Loop from
i=0
toi<array.length
. - Check
if(array[i]==searchElement)
. If yes, then assignfound=true
andbreak
out of the loop. - End loop.
- Check if(found) then print “Found” else print “Not Found”.
Here is the implementation of the steps in C and Java:
C
//C Program of Linear Search
#include <stdio.h>
#include <stdlib.h>
int main()
{
int array[10];
printf("Enter 10 numbers \n");
for(int i=0; i<10; i++){
scanf("%d",&array[i]);
}
int found=0, searchElement;
printf("Enter an Number to search \n");
scanf("%d",&searchElement);
//Linear Search
for(int i=0; i<10; i++){
if(searchElement == array[i]){
found = 1;
break;
}
}
if(found){
printf("%d Found \n",searchElement);
}
else{
printf("%d Not found \n",searchElement);
}
return 0;
}
Java
import java.util.Scanner;
public class Main {
static Scanner in= new Scanner(System.in);
public static void main(String args[]){
int[] array= new int[10];
System.out.println("Enter 10 numbers ");
for(int i=0; i<10; i++){
array[i] = in.nextInt();
}
System.out.println("Enter an Number to search ");
int searchElement = in.nextInt();
boolean found = false;
//Linear Search
for(int i=0; i<10; i++){
if(searchElement==array[i]){
found = true;
break;
}
}
if(found){
System.out.println("Found "+ searchElement);
}
else{
System.out.println("Not found");
}
}
}
Output:
In the above program, found
variable stores the result whether the element is present in the array or not.
If the value of found
is true or 1 then it means the search element is present in the array otherwise not.
The time complexity for Linear Search is O(n).
Linear search is efficient to use with the small dataset. For large array, the time complexity of the algorithm increases linearly.
In this tutorial, we learned what is Linear search algorithm, how it works, and how to use a linear search algorithm to search an element in an array with C and Java examples.