/* BINARY SEARCH */
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,loc,mid,beg,end,flag=0,item;
clrscr();
printf("\n\t\tINPUT:");
printf("\n\t\t------");
printf("\n\t\tEnter the number of elements: ");
scanf("%d",&n);
printf("\n\t\tEnter the elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n\t\tEnter the element to be search: ");
scanf("%d",&item);
loc=0;
beg=0;
end=n-1;
printf("\n\t\tOUTPUT:");
printf("\n\t\t-------");
while((beg<end)&&(item!=a[mid]))
{
mid=((beg+end)/2);
if(item==a[mid])
{
printf("\n\t\tSearch is successful.");
loc=mid;
printf("\n\t\tPosition of the item is:
%d",loc+1);
flag=flag+1;
}
else if(item<a[mid])
end=mid-1;
else
beg=mid+1;
}
if(flag==0)
{
printf("\n\t\tSearch is not successful.");
}
getch();
}
INPUT:
------
Enter the number of elements: 5
Enter the elements:
354
234
22
575
45
Enter the element to be search: 22
OUTPUT:
-------
Search is successful.
Position of the item is: 3
INPUT:
------
Enter the number of elements: 5
Enter the elements:
23
42
54
65
24
Enter the element to be search: 30
OUTPUT:
-------
Search is not successful
No comments:
Post a Comment