C Program to implement Binary Search...

#include<stdio.h>

int binarysearch(int a[],int n,int key)
{
 int beg,end,mid;
 beg=0;
 end=n-1;
 while(beg<=end)
 {
 mid=(beg+end)/2;
 if(key==a[mid])
 return mid;
 else if(key>a[mid])
 beg=mid+1;
 else
 end=mid-1;
 }
 return -1;
}

void main()
{
 int a[100],n,i,key;
int pos;
 printf("Enter the no of elements of the Array..");
 scanf("%d",&n);
 printf("\nEnter the elements one by one in ascending order..");
 for(i=0;i<n;i++)
  scanf("%d",&a[i]);
 printf("\nEnter the element to search..");
 scanf("%d",&key);
 pos=binarysearch(a,n,key)+1;
 if(pos==0)
  printf("\nThe element is not found..");
 else
  printf("\nThe element is found in the position is %d",pos);
}

No comments:

Post a comment