C or C++ Program for Binary search

This article show C/C++ Program for Binary search. Before start let us discuss about binary search.

What is Binary Search?
Binary search is one kind of searching algorithm.It is very important.

C/C++ Code for Binary search

#include
#include
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();
}

Leave a Reply

Your email address will not be published. Required fields are marked *