Wednesday 2 July 2014

Binary search



Remember that Binary search is used only for sorted array.

#include<conio.h>
#include<stdio.h>
main()
{
int n;
puts("enter the size of the array");
scanf("%d",&n);
int i,arr[n],fst,lst,mid,val;
puts("enter the increasing sorted numbers in the array");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
puts("enter the value to be searched");
scanf("%d",&val);
fst=1;
lst=n;
while(fst<lst)
{
mid=(fst+lst)/2;
if(arr[mid]==val)
printf("\nelment found at %d",mid+1);

else if(arr[mid]>val)
lst=mid-1;
else
fst=mid+1;

}
if(fst>lst)
puts("not found");
getch();
return 0;
}

No comments:

Post a Comment