/*linear search*/
#include <stdio.h>
#include <conio.h>
#include <math.h>
int start,middle,end;
void main()
{
char q;
int a[50],b[50],c[50],i,j,n,t,tmp;
clrscr();
printf ("\nEnter number of elements :");
scanf ("%d",&n);
for (i=0;i<n;i++)
{
printf ("Enter %d element :",i+1);
scanf ("%d",&a[i]);
b[i]=i+1;
c[i]=a[i];
}
/*arranging in ascending order*/
for (t=0;t<n;t++)
{
for (i=t+1;i<n;i++)
{
if (c[i]<c[t])
{
tmp=c[t];
c[t]=c[i];
c[i]=tmp;
tmp=b[t];
b[t]=b[i];
b[i]=tmp;
}
}
}
/*end of arrangment*/
do
{
printf ("\nEnter element to be searched :");
scanf ("%d",&j);
start=0;
end=n-1;
middle=floor((start+end)/2);
for (;c[middle]!=j && start<end;middle=floor((start+end)/2))
{
if (c[middle]>j)
end=middle;
if (c[middle]<j)
start=middle+1;
}
if (c[middle]==j)
printf ("\nElement %d is found in list at position %d",j,b[middle]);
else
printf ("\nElement %d not found.",j);
printf ("\nDo u want to continue :");
q=getche();
}while (q=='y' || q=='Y');
getch();
}
Output
Enter number of elements :5
Enter 1 element :7
Enter 2 element :3
Enter 3 element :8
Enter 4 element :6
Enter 5 element :11
Enter element to be searched :8
Element 8 is found in list at position 3
Do u want to continue :y
Enter element to be searched :12
Element 12 not found.
Do u want to continue :y
Enter element to be searched :7
Element 7 is found in list at position 1
Do u want to continue :