Friday, 16 December 2016

Binary Search

        #include<iostream.h>
              #include<conio.h>
     #include<process.h>
int Bsearch (int A [], int N, int item)
{       {    
       int beg=0, last=N-1, mid;
      while(beg<=last)
 {      {
       mid= (beg last)/2;
        if(item==A[mid])
         return mid;
       else if(item<A[mid])
       last=mid-1;
       else
       beg=mid+1;
       }
        return -1;
           }
i           int A [50], N, i, item, index;
           char choice;

       void main ()
        { clrscr();   
       cout<<"\n\tEnter the size of array(max.50):";
        cin>>N;
         cout<<"\n\tEnter the array:";
         cout<<"\n";
         for (i=0; i<N; i++) 
      {
       cout<<"\t";
       cin>>A[i];
 }
       cout<<"\n\tThe array is:  ";
       for (i=0; i<N; i++)
        {
        cout<<"  ";
        cout<<A[i]<<"\t"; }
 do
 {
        cout<<"\n\tEnter the element to be searched :";
        cin>>item;
       index=Bsearch (A, N, item);
        if(index==-1)
        cout<<"\n\tElement not found";
        else
       cout<<"\n\tElement found at location :"<<index+1;
      cout<<"\n\tWant to search again(Y/N) : ";
      cin>>choice;
 }      while(choice=='Y'||choice=='y');
      getch();}


No comments:

Post a Comment