Sei sulla pagina 1di 17

# Searching Algorithm

Linear Search
Linear Search
In this searching technique we compare the elements of
the array one-by-one with the key element we are
looking for.
It is a very simple searching algorithm but takes a lot of
time.
If the key element is present in the array then the
search is successful else not.
Example
Consider an array arr having 5 elements
5 4 3 1 2

## In the worst case it will take 5 comparison as there are

5 elements.
Searching for 2

Given array 5 4 3 1 2

KEY ELEMENT
2 Is 2 found?

No

5 4 3 1 2
Searching for 2

Given array 5 4 3 1 2

KEY ELEMENT
2 Is 2 found?

No

5 4 3 1 2
Searching for 2

Given array 5 4 3 1 2

## KEY ELEMENT Is 2 found?

2
No

5 4 3 1 2
Searching for 2

Given array 5 4 3 1 2

## Is 2 found? KEY ELEMENT

2
No

5 4 3 1 2
Searching for 2

Given array 5 4 3 1 2

## Is 2 found? KEY ELEMENT

2
Yes

5 4 3 1 2
Searching for 2

Given array 5 4 3 1 2

## Search successful! KEY ELEMENT

KEY at index 4
Note! Array index starts from 0
2

5 4 3 1 2
• Linear search is also known as sequential search.
• If there are n elements in array then, in the best case
key is found in 1 comparison. While in the worst case it
takes n comparison.
• Best case occurs when the key element is either at the
last position of the array
• In the worst case the key element is either at the last
position or not present in the array.
Algorithm
/*a[0:n-1] is an array of n elements. Key is the element being searched.
*/
LinearSearch(a,n,key)
Begin
for i=0 to n-1 by 1 do
if a[i] == key then
return i; //returning index of the array
endif
endfor
return -1;
End
Order of Linear Search

## If there are n elements in the array

Then, in best case we need 1 comparison so, order is
O(1)
While in the worst case we need n comparison so,
Order is O(n)
Note! While starting the order we will take the worst
case so, order of linear search is O(n)
Write a program in C to enter 5
elements and search for a key
element
/* linear search example
*/

#include<stdio.h>

//function declaration
int linearsearch(int *a,int n,int key);

int main(){
//variable declaration
int arr[5],i,key;
//input
printf("Enter the array elements: ");
for(i=0;i<5;i++)
scanf("%d",&arr[i]);
printf("Enter key: ");
scanf("%d",&key);

//search
i=linearSearch(arr, 5, key);
//output
if(i == -1)
else
printf("key at index: %d\n", i);
return 0;
}
//function definition
int linearSearch(int *a, int n, int key){
int i;
for(i=0;i<=n-1;i++){
if(a[i] == key)
return i;
}
return -1;
}