Hey guys, I'm trying to program which finds the closest value stored in a sorted array using binary search. In other words, it should read the middle array and then move to the middle of the half where this value should be (unless the closest value is in the middle already). Anyway, my program doesn't seem to be working properly and i'm getting a bit frustrated, could you possibly push me in the right direction?
so for example, this is my array
data[] = ( 2.53 3.24 4.71 7.35 7.58 7.89 9.83 12.03 19.4 23.08 4.5 )
and when I say i want to find a value closest to 4.5, it should say that its stored in data [2] but I get data[6] for some reason
Thanks :)
public static int binary (double [] data, int a,int b, double elem)
{ // start binary
int left = a;
int right = b;
while ( left < right)
{
int middle = (left+right)/2;
double i = Math.abs(data [middle]- elem);
double j = Math.abs(data [middle+1]- elem);
double k = Math.abs(data [middle-1]- elem);
if (k > i && j > i)
return middle;
else if ( k < i && k < j)
left = middle - 1;
else if ( j < i && j < k)
right = middle+1;
}
return left; //The program should always find a closest value but a return statement is required
// or what?
}