Binary search source code
#include<stdio.h>
#include<conio.h>
void main()
{
int n,item,num[100],t,i,j,beg,end,mid;
clrscr();
printf(" How many numbers : ");
scanf("%d",&n);
printf(" Enter numbers: ");
for(i=0;i<n;i++)
scanf("%d",&num[i]);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(num[i]>num[j])
{
t=num[i];
num[i]=num[j];
num[j]=t;
}
printf("nAll number after sorting :n ");
for(i=0;i<n;i++)
printf(" %d ",num[i]);
printf("nEnter the number you want to search: ");
scanf("%d",&item);
beg=0;
end=n-1;
while(beg<=end)
{
mid=(beg+end)/2;
if(item<num[mid])
end=mid-1;
else if(item>num[mid])
beg=mid+1;
else if(item==num[mid])
{
printf(" n%d is found at position : %d",item,mid+1);
break;
}
}
if(item!=num[mid])
printf("n Not found this number");
getch();
}
0 comments:
Post a Comment
If you have any confusion, Please leave a comment. I will assist you. Do not include any URL in comments.