as usual, I searched on Google and here for an answer, but could not find anything that helped me. Keep in mind this is NOT for homework, I am studying the test and struggling to answer this question. There, the array is alternately sorted, that is, even index elements are sorted, and elements of the odd index are also sorted (from the minimum to the largest number). For instance:
int a[] = {1,2,5,3,6,10,9};
Now the question is asked to write a logical method that receives an array and a number, x and returns true if the number is a possible combination of two adjacent "tiles" and false if not. For instance:
x = 9;
FindX(a,9) -> true;
a[3](3) + a[4](6) = 9.
I wrote my method and it seems to work with the IS number of a possible combo, but when it should return false, it gets stuck when the number is in the range of 2 possible combos.
public static boolean FindX(int a[], int x){
if (a.length==1) {
return false;
}
int i=(a.length-1)/2;
int i2=i+1;
for (; i>=0 && i2<a.length;){
if (a[i]+a[i2]==x) {
return true;
}
else if (a[i]+a[i2]>x){
i = (i/2)+1;
i2 = i+1;
}
else if (a[i]+a[i2]<x){
i = (i2+a.length)/2;
i2 = i+1;
}
}
return false;
}
Whenever I enter a possible combination, it works. But if, for example, I put 14, and I'm between 9 (= a [3] (3) + a [4] (6) ) and 16 (= a [4] (6) + a [5] (10) ), it loops forever, and I can’t come up with the right way out when this happens. If the number of possible combos, but not in the range, it returns false, but for intermediate numbers I get stuck. The answer should be as effective as possible in memory and in time.
Thanks in advance.