Pages

Ads 468x60px

Saturday, 2 June 2012

C Program For BINARY SEARCH.




C Program For BINARY SEARCH



C program for binary search: This code implements binary search in c language. 
It can only be used for sorted arrays, but it's fast as compared to linear search.
 If you wish to use binary search on an array which is not sorted then you must
 sort it using some sorting technique say merge sort and then use binary search 
algorithm to find the desired element in the list. If the element to be searched is 
found then its position is printed.

CODE:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,search,f=0,low,high,mid,a[20];
clrscr();
printf("Enter the n value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the number in ascending order a[%d]=",i);
scanf("%d",&a[i]);
}
printf("Enter the search element:");
scanf("%d",&search);
low=1;
high=n;
while(low<=high)
{
mid=(low+high)/2;
if(search<a[mid])
{
high=mid-1;
}
else if(search>a[mid])
{
low=mid+1;
}
else
{
f=1;
printf("obtainedin the position %d:",mid);
getch();
exit();
}
}
if(f==0)
{
printf("not present");
}
getch();
}

0 comments:

Post a Comment

Total Pageviews