I am trying to tackle a classical interview problem which is basically performing a binary search on a list which first increases then decreases. Even though it's obvious that we can achieve O(log n) I couldn't figure out what is wrong the code below that I've written:
#include <iostream>
using namespace std;
int binarySearch(int *A, int low, int high, int key)
{
while(low < high)
{
int mid = (low + high) / 2;
if(key < A[mid])
{
if(A[mid - 1] < A[mid] && A[mid] < A[mid + 1])
high = mid - 1;
else
low = mid + 1;
}
else if(key > A[mid])
{
if(A[mid - 1] < A[mid] && A[mid] < A[mid + 1])
low = mid + 1;
else
high = mid - 1;
}
else
return mid;
}
return -(low + 1);
}
int main()
{
const int SIZE = 8;
int A[SIZE] = {3,5,7,14,9,8,2,1};
cout<<binarySearch(A, 0, SIZE, 14);
return 0;
}
The reason why I ask this question is because I wonder two things. 1) What is wrong with the code since it fails for some values such as "14". 2) Can it be improved?
(low + high) / 2
. – Nathan Ernst Jun 27 '13 at 19:36