/*LINEAR SEARCH for numbers*/
#include <stdio.h>
int stepcount=0,swapcount=0,compcount=0;
int linsearch(int a[],int n , int key);
void main()
{
int a[30],key,n,i,result;
printf("\n Enter No. of elements : ");
scanf("%d" ,&n);
printf("\n Enter a list of %d elements : ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Enter the the element to be searched :");
scanf("%d",&key);
result=linsearch(a,n,key);
if(result==-1)
printf("\n Not found ");
else
printf("\n Found at location= %d",result);
printf("\n No. of steps= %d",stepcount);
printf("\n No. of swaps= %d", swapcount);
printf("\n No. of comparisons= %d",compcount);
}
int linsearch(int a[],int n , int key)
{
int i;
for(i=0;i<n;i++)
{
compcount++;
stepcount+=2;
if(a[i]==key)
{
stepcount++;
return(i+1);
}
}
return(-1);
}
No comments:
Post a Comment