Sunday, January 6, 2013

Program for Binary Search



C/C++ Program for Binary Search



#include<iostream.h>
#include<conio.h>
int main(){
clrscr();
int n,i,beg,end,mid,data[20],loc,item;

     cout<<"     \" This program will performs Binary search. \""<<endl<<endl;

     xx:
    cout<<"How many numbers ?. Give a integer number."<<endl;
    cin>>n;

    if(n<0) {
    cout<<"Negative number is not allow, Please give a integer number"<<endl<<endl;
    goto xx;
    }

    else if(n==0) {
    cout<<"0 is not allow"<<endl<<endl;
    goto xx;
    }

     yy:
    cout<<"What are the elements ?. Give some sorted data"<<endl;
    for(i=1;i<=n;i++)
    cin>>data[i];

    for(i=1;i<n;i++)
    if(data[i] > data[i+1]) {
    cout<<"Non sorted data is not allow.Please give sorted data."<<endl;
    goto yy;
    }

     cout<<"Give a data that you want to search."<<endl;
     cin>>item;

     beg=1;
     end=n;
     mid=(beg+end)/2;

     while(data[mid]!=item && beg<=end) {
    if(item<data[mid])
    end=mid-1;
    else beg=mid+1;
    mid=(beg+end)/2;
    }

     cout<<endl;
     if(data[mid]==item) {
    loc=mid;
     cout<<item<<" is present here ( ";
     for(i=1;i<=n;i++)
     cout<<data[i]<<" ";
     cout<<") and it's position is : "<<loc;
     }

     else {
     cout<<item<<" is not present here ( ";
     for(i=1;i<=n;i++)
     cout<<data[i]<<" ";
     cout<<")";
     }

getch();
}


For more please visit cybarlab.com

No comments:

Post a Comment