Program to search an integer in an array of N integer using binary search method

Wednesday, March 04, 2020

//program to search an integer in an array of N integer using binary search method
#include<iostream.h>
#include<conio.h>
int Binary_Search(int a[],int n,int element);
void main()
{ clrscr();
  int A[20],N,ELEMENT,i,INDEX;
  cout<<"\n Enter the number of elements:";//Ascending order
  cin>>N;
  cout<<"\n Enter the elements of array:";
  for(i=0;i<N;i++)
  { cout<<"\n Enter A["<<i<<"]:";
cin>>A[i];
  }
  cout<<"\n Enter the element to be searched:";
  cin>>ELEMENT;
  INDEX=Binary_Search(A,N,ELEMENT);
  if(INDEX==-1)
  cout<<"\n Unsuccessful search";
  else
  cout<<"\n Element is present at "<<INDEX<<" and  is at position "<<(INDEX+1);
  getch();
}

int Binary_Search(int a[],int n,int element)
{ int beg=0,last=n-1,mid;
  while(beg<=last)
  { mid=(beg+last)/2;
if(a[mid]==element)
return mid;
else
if(a[mid]<element)
beg=mid+1;
else
last=mid-1;
  }
  return(-1);
}

You Might Also Like

0 Comments

Like us on Facebook

Flickr Images

Flickr Short Films