Tuesday, June 29, 2010

Binary Search-C++

 Compare the target to the middle item in the list. If the target is the
same as the middle item, you've found the target. If it's before the
middle item, repeat this procedure on the items before the middle. If
it's after the middle item, repeat on the items after the middle
 
Worst case performance O(log n)
Best case performance O(1) 
Code: 
#include<iostream>
#include<stdlib.h>

using namespace std;

class BinSearch
{
private:
double *Plist;


public:
BinSearch(double *,int);
void BinSrch(int, int, double);
~BinSearch();
};

BinSearch::BinSearch(double *list, int ListLong)
{
Plist = new double[ListLong];

for(int i=0;i<ListLong;i++) Plist[i]=list[i];
}

BinSearch::~BinSearch()
{
delete []Plist;
}

void BinSearch::BinSrch(int s, int r, double x)
{

int m;
m=(s+r)/2;
if(Plist[m]==x)
{


cout<< "The order of " <<x<<" is "<<m+1<<" in this sequence."<<endl;
return;
}

else if (s>=r)
{
cout<<x<<"does not exist in the sequence"<<endl;
exit(-1);
}

else if (x>Plist[m])
BinSrch(m+1,r,x);

else
BinSrch(s,m-1,x);
}


int main()
{
//a should be in the order of increasing
        double a[]={2.1,2.3,2.5,2.7,2.9,3.1,3.3,3.5,3.7,3.9};

double x=2.3;
int s=0, r=9;

BinSearch bs(a,10);
bs.BinSrch(s,r,x);

return(0);
}

1 comment:

  1. Your program will go out of bounds for an empty array

    ReplyDelete