Tuesday 21 October 2014

Binary search program in C++

C++ program to implement binary search program in C++.


C++ program to implement Non recursive binary search algorithm

#include<iostream>
using namespace std;
class search_list
{
    int data[20];
    int n;
public:
    void get_data();
    void binary_search();
};
void search_list::get_data()
{
    cout<<"How many elements two be entered ";
    cin>>n;
    cout<<"Enter the elements in increasing order ";
    for(int i=0;i<n;i++)
        cin>>data[i];
}
void search_list::binary_search()
{
    int item,mid,last=n-1,first=0;
    cout<<"Enter the element to be searched ";
    cin>>item;
    while(first<=last)
    {
        mid=(first+last)/2;
        if(data[mid]==item)
        {
            cout<<"Element is present at "<<mid+1<<" position";
            break;
        }
        else if(item<data[mid])
            last=mid-1;
        else
            first=mid+1;
    }
    if(first>last)
        cout<<"Element is not present";
}
int main()
{
    search_list search;
    search.get_data();
    search.binary_search();
    return 0;
}



C++ program to implement recursive binary search algorithm

#include<iostream>
using namespace std;
class search_list
{
    int data[20];
    int n,item;
public:
    void get_data();
    void binary_search(int,int);
};
void search_list::get_data()
{
    cout<<"How many elements two be entered ";
    cin>>n;
    cout<<"Enter the elements in increasing order ";
    for(int i=0;i<n;i++)
        cin>>data[i];
    cout<<"Enter the element to be searched ";
    cin>>item;
    binary_search(0,n-1);
}
void search_list::binary_search(int first,int last)
{
    int mid=(first+last)/2;
    if(first>last)
    {
        cout<<"Element not found";
        return ;
    }
    else if(data[mid]==item)
    {
        cout<<"Element is present at "<<mid+1<<" position";
        return;
    }
    else if(item<data[mid])
        binary_search(first,mid-1);
    else
        binary_search(mid+1,last);
}
int main()
{
    search_list search;
    search.get_data();
    return 0;
}

2 comments:

  1. Hi there colleagues, how is the whole thing, and what you wish for to say about this article, in my view it in fact amazing for me. How To Password Protect Folder When Nobody Else Will.

    ReplyDelete
  2. Great blog! I love reading your articles.
    www.lge.com.pl

    ReplyDelete