Binary Search Algorithm using c/c++
Binary Search Algorithm using c/c++
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.
Binary search Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,x;
void sorts(int [],int);
int binser(int [],int,int,int);
clrscr();
printf("How many Element are insert? ");
scanf("%d",&n);
printf("Enter Element");
for(i=0;i<n;i++)
{
printf("\nEnter Element %dth : ",i);
scanf("%d",&a[i]);
}
sorts(a,n);
printf("\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\nEnter Find Elements : ");
scanf("%d",&x);
i = binser(a,0,n,x);
if(i==0)
printf("\nYour Element not found");
else
printf("\nYour Element found possion is : %d",i);
getch();
}
int binser(int a[],int l,int h,int x)
{
int mid;
if(l==h)
{
if(x=a[l])
return l+1;
else
return 0;
}
else
{
mid=(l+h)/2;
if(x==a[mid])
return mid+1;
else if(x<a[mid])
return binser(a,l,mid-1,x);
else
return binser(a,mid+1,h,x);
}
}
void sorts(int a[],int n)
{
int i,j,tmp;
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
if(a[i]>a[j])
{
tmp=a[j];
a[j]=a[i];
a[i]=tmp;
}
}
}
}
Comments
Post a Comment