Saturday, August 11, 2012

Binary Search in C++


#include
#include


void binsearch(int ar[],int size,int ele)
{       int lb=0,ub=size-1,mid;             //lb=>lower bound,ub=>upper bound

     for(;lb
       {
           mid=(lb+ub)/2;

           if(ar[mid]==ele)
             {
                cout<<"\n SEARCH SUCCESSFUL";
                break;
             }

           else
                 if(ar[mid]
                 ub=mid-1;

           else
      if(ar[mid]>ele)
      lb=mid+1;
      }

       if(ub

         cout<<"\n SEARCH UNSUCCESSFUL";

}

void sort(int ar[],int size)               //sorts the array in ascending array using bubble sort
{
 int temp;

 for(int i=0;i
for(int j=0;j
if(ar[j]>ar[j+1])
{
temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;

}

}

void display(int ar[],int size)
{
 for(int i=0;i
cout<<'\n'<
}

void input(int ar[],int size)
{
 for(int i=0;i
cin>>ar[i];
}

void main()
{
 clrscr();

 int size;
 cout<<"\n ENTER THE NUMBER OF ELEMENTS REQUIRED IN THE ARRAY :";
 cin>>size;

 int *ar=new int(size);

 cout<<"\n ENTER THE ELEMENTS OF THE ARRAY :\n";

 input(ar,size);         //takes the input from the array

 sort(ar,size);         //sorts the array in the ascending order

 int ele;
 cout<<"\n ENTER THE ELEMENT TO BE FOUND :\n";
 cin>>ele;
 binsearch(ar,size,ele);
 getch();

}

No comments:

Post a Comment