You all will agree to this that linear search is the most simple search algorithm we have read among all other algorithms. Right!?! In this type of search , every item in a list is checked one by one, i.e, a sequential search is made over all items in a list. And if a match is found, that is, the item we a looking for is found then that particular item is returned otherwise the search continues till the end of the list.
Algorithm:
Linear Search(Array arr, Value item)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if arr[i] = item then go to step 6
Step 4: Set i to i + 1
Step 5: Go to step 2
Step 6: Print element item found at index i and go to step 8
Step 7: Print "element not found"
Step 8: Exit
In a list with n items, the best case will be the search to be found at first element of the list as that will be the only comparison needed. The worst case will be the case when the value is not in the list or it occurs once at the last of the list, as in this case n comparisons will be needed.
/* Program to search an element in an array of integers using linear search technique */
#include <stdio.h>
#define MAX 100
void main (void)
{
int a[MAX], i=0, n ,item;
printf(\n Enter the size of array:);
scanf(%d, &n);
if(n > MAX)
{
printf(\n Array size input is greater than the declared size\n);
exit(1);
}
printf(Enter the %d elements of an array:,n);
scanf(%d,&a[i]);
printf(Enter the element to be searched:);
scanf(%d,&item);
while((i < n) && a[i] != item)
i++;
if(i > n)
{
printf(\n Element %d you are looking for is not in the list.,item);
}<br>
else
printf(\n %d found at index %d of an array,item,n);
}
0 Comment(s)