Write a program using binary search algorith.
Program:
#include<stdio.h>
main()
{
int x[100], beg, end, mid, item, loc, n, i;
printf("How many number =");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
printf("X[%d]=",i);
scanf("%d", &x[i-1]);
}
printf("\n Put the number that you want to search = ");
scanf("%d", &item);
beg=0;
end=n-1;
mid=int((beg+end)/2);
while(beg<=end && x[mid]!=item)
{
if(item<x[mid])
end=mid-1;
else
beg=mid+1;
mid=int((beg+end)/2);
}
if(x[mid]==item)
printf("Item found");
else
printf("Item not found");
}
Program:
#include<stdio.h>
main()
{
int x[100], beg, end, mid, item, loc, n, i;
printf("How many number =");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
printf("X[%d]=",i);
scanf("%d", &x[i-1]);
}
printf("\n Put the number that you want to search = ");
scanf("%d", &item);
beg=0;
end=n-1;
mid=int((beg+end)/2);
while(beg<=end && x[mid]!=item)
{
if(item<x[mid])
end=mid-1;
else
beg=mid+1;
mid=int((beg+end)/2);
}
if(x[mid]==item)
printf("Item found");
else
printf("Item not found");
}