Binary search
class MainClass {
public static void main(String[] args) {
double[] x = { -39, -3, 6, 10, 4, 9, 10 };
double value = 8;
int lower = 0, upper = x.length - 1;
while (lower <= upper) {
int middle = (lower + upper) / 2;
if (value > x[middle])
lower = middle + 1;
else if (value < x[middle])
upper = middle - 1;
else
break;
}
if (lower > upper)
System.out.println("Not found");
else
System.out.println("Found");
}
}
Related examples in the same category