Sunday, 2 September 2012

Binary Search

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

class binary
{
private:
    int a[10],n,mid,l,u,num,flag;
public:
    void read();
    void search();
};
void binary::read()
{
    cout<<"Enter how many numbers : ";
    cin>>n;
    cout<<"Enter the numbers in sorted order : ";
    for(int i=0;i<n;i++)
    cin>>a[i];
}
void binary::search()
{
    cout<<"Enter an element to search : ";
    cin>>num;
    l=0;
    u=n;
    while(l<=u)
    {
        flag=0;
        mid= int((l+u)/2);
        if(a[mid]==num)
        {
         cout<<"Search is find at "<<mid+1<<" position";
         flag=1;
         break;
        }
        if(num>a[mid])
        l=mid+1;
        if(a[mid]>num)
        u=mid-1;
    }
    if(flag==0)
      cout<<num<<" is not found";
}

void main()
{
     binary b;
     clrscr();
     b.read();
     b.search();
     getch();
}



No comments:

Post a Comment