I have an school assignement that requires me to create a recursive Binary search function. I'm not allowed to change the function signature. My experience with pointer isn't the best and i think my problem lies there. I get an Stackoveflow but i dont really understand way
bool contains(const int* pBegin, const int* pEnd, int x)
{
int length = pEnd - pBegin;//gives me the length of the array
const int* pMid = pBegin + (length / 2);
if(length == 1)
{
if(*pMid != x)
return false;
return true;
}
else if(x < *pMid)
return contains(pBegin, pMid-1, x);
else
return contains(pMid, pEnd, x);
}
void main(){
setlocale(LC_ALL, "swedish");
int arr[10];
for(int i = 0; i < 10; ++i)
arr[i] = i;
bool find = contains(&arr[0], &arr[10], 3);//arr[10] points to the index after the array!
cout <<"found = "<< find << endl;
system("pause");
}
Can somebody please explain to me what I'm doing wrong, and how i could do it in a better way?
contains, which callscontains, which callscontains, etc. and never getting out of this call chain until the stack overflows.int arr[10]and instead usestd::vector<int> arr.std::arraybut it is not a problem.std::vectoris going to require dynamic allocation and there is no reason to pay for that if it is not needed.