Binary Search

Greetings everyone,
I am a newbie at programming. After some weeks from starting, i decided to have a go at binary search. This is what i have came up with after a while. The program works but i just need advice from experienced programmers whether this is the correct way to program...is this programming acceptable. I would like to hear what i can improve on this code. Thanks a lot.


[pls don't mind my english]


#include<iostream>
using namespace std;

bool binsearch(int* a, int num,int begin, int end)
{
int mid = (begin + end) /2;

if(num == a[mid])
return true;
else if(a[mid-1] < num && a[mid] > num)
return false;
else if(num < a[0] || num > a[end])
return false;
else if ( num < a[mid])
return binsearch(a,num,begin,mid);
else if(num > a[mid])
return binsearch(a,num,mid+1,end);


}



int main()
{
int a[9];int temp;
int x;

for(int i=0;i<9;i++)
a[i] = rand();

for(int i=0;i<9;i++)
{
for(int j=i+1;j<9;j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}

}


for(int i=0;i<9;i++)
cout<<a[i]<<' ';

cout<<endl;

while(x!=-1){
cout<<"ENTER(enter -1 to exit): ";
cin>>x;



if(binsearch(a,x,0,8))
cout<<"\t\tNUMBER EXISTS\n";
else
cout<<"\t\tNUMBER DOES NOT EXIST\n";
if(x==-1)
{
cout<<"\t\tEXITING\n";
break;
}
}


system("pause");
}
When you post code, put it in [code][/code] tags.

There really isn't much that can be told from a small project like this ..

Your algorithm isn't perfect.
num < a[0] || num > a[end] condition is bad. There should be 'begin' instead of 0 . And even then, it is redundant. It will never return true (except for the first iteration).
a[mid-1] < num && a[mid] > num isn't great either. What if mid is 0 ? Even though it might save some time, it isn't necessary. I really can't say if this is more harm or profit.
The remaining three conditions are sufficient for binary search.
Though if the first and the fourth conditions return false, you don't need to check the last one. You know what it will return ..

Also, unless you do it for practice or require some special optimizations, don't implement the trivial algorithms, such as sorting, yourself. You can find implementations in <algorithm>.

Also, you shouldn't be calling binsearch if the user enters -1 ..
Last edited on
Got that thnanks alot
Topic archived. No new replies allowed.