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);
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 ..