Hi! I have written a binary search function which finds the last occurrence of a number in an array. When I test it, it always seems to give the correct output. The problem is that a window pops up in Visual Studio saying, "Debug Error!. . . HEAP CORRUPTION DETECTED." I am assuming the problem lies in running out of bounds in the array. I have tried adjusting the bounds on the for loop and I have run the code through the debugger a bunch of times, but I cannot locate the problem.
#include <iostream>
usingnamespace std;
int maxNum, mid, number = 0, result = -1;
int* ptr = NULL;
int binarySearchFirstLastOccurance();
int main()
{
cout << "How many numbers do you want to enter? ";
cin >> maxNum;
ptr = newint[maxNum];
cout << "Enter values in ascending order. May use more than one occurance of the same "
<< "number as long as they are consequative." << endl;
for(int count = 0; count < maxNum; count++) {
ptr[count] = 0;
}
for (int count = 1; count <= maxNum; count++) {
cin >> ptr[count];
}
for (int count = 1; count <= maxNum; count++) {
cout << ptr[count] << " ";
}
cout << "\nWhat number do you want to search for? ";
cin >> number;
if (binarySearchFirstLastOccurance() > 0)
cout << "\nThe last occurance of this value is located in the number " << result << " element." << endl;
else cout << "\nThat number is not in the array." << endl;
delete[] ptr;
return 0;
}
int binarySearchFirstLastOccurance( )
{
int left = 1, right = maxNum;
while (left <= right) {
mid = (left + right) / 2;
if (number == ptr[mid]) {
result = mid;
left = mid + 1;
}
elseif (number < ptr[mid])
right = mid - 1;
else left = mid + 1;
}
return result;
}
How exactly is your binary search going to find the last matching value? Think about it. What if the array contains 5, 5, 5, 5, 5 and you search for 5?
@salem
I had tried that earlier too, but then I wasn't getting the correct output. However, I adjusted my for loops back like you mentioned, just you saying that was enough to steer me in the direction of looking at my algorithm closer. I adjusted my result variable to result = mid + 1 and it seems to be working now.
I actually intend to use parameters, but just wanted to make sure I had the algorithm working correctly first.