All rights are reserved by Niteesh Kumar.. Theme images by Storman. Powered by Blogger.

Followers

Total Pageviews

Blog Archive

Follow by Email

Translate

Wednesday, 30 April 2014

Binary search c++ program in data structure


c++ code is given below

#include<iostream.h>
#include<conio.h>
int bsearch(int[],int,int);
void main()
{clrscr();
 int ar[50],item,n,index;
 cout<<"\n enter the size of array :";
 cin>>n;
 cout<<"\n enter the elements of the array:";
 for(int i=0;i<n;i++)
 cin>>ar[i];
 cout<<"\n enter the elements to be searched:";
 cin>>item;
index= bsearch(ar,n,item);
 if(index==-1)
 cout<<"\n sorry the no. is not found";
  else
 cout<<"\n element found at index:"<<index<<" position"<<index+1;
 getch();
 }
 int bsearch(int ar[],int n,int item)
 {int beg,last,mid;
  beg=0;
  last=n-1;
  while(beg<=last)
  {
                mid=(beg+last)/2;
                if(item==ar[mid])
                return mid;
                else if(item>ar[mid]) beg=mid+1;
                else  last=mid-1;
  }
  return -1;
 }
OUTPUT-1-

 enter the size of array :5

 enter the elements of the array:12 23 34 45 56

 enter the elements to be searched:34

 element found at index:2 position3
OUTPUT-2-

 enter the size of array :5

 enter the elements of the array:12 23 34 45 56

 enter the elements to be searched:58

 sorry the no. is not found


0 on: "Binary search c++ program in data structure "