/*C Program to implement binary search*/
#include<stdio.h>
#include<conio.h>

int binsearch(int a[],int n,int key)
{
 int low,high,mid;
 low=0;
 high=n-1;
 while(low<=high)
 {
  mid=(low+high)/2;
  if(key<a[mid]) high=mid-1;
  else if(key>a[mid])  low=mid+1;
  else return mid;
 }
 return -1;
}
void main()
{
  int n,i,pos,key,a[20];
  clrscr();
  printf("\n\n\tHow many elements?  ");
  scanf("%d", &n);
  printf("\tEnter %d elements in ascending order:\n\t",n);
  for(i=0;i<n;i++)
  scanf("%d", &a[i]);
  printf("\tWhich element is to be searched?  ");
  scanf("%d", &key);
  pos=binsearch(a,n,key);
  if(pos==-1)
  printf("\tSorry! Element not found");
  else
  printf("\n\t\tSuccess ! \n\t%d found at position %d", key,pos+1);
  getch();
}
