I came across the following problem:
Now you a given array of double number of length n (n is known) as double sample[n]
, and it is in ascending order (all elements are different). Please write a function with one parameter double num
, which return the index of the element in sample[n]
which is closest to the parameter num
. If num
is located exactly in the middle of one interval, return the index of the element smaller than it.
Here is my code in Java:
public int getIndex(double num) {
if(sample[0] >= num) {return 0;}
for(int i = 1, i < sample.length; i++) {
if(sample[i] == num) {return i;}
else if(sample[i] > num) {
return (sample[i]-num) < (num-sample[i-1]) ? i : i-1;
else {continue;}
}
return sample.length;
}
It is clearly linear complexity. However, I was told by my teacher that algorithm with O(log n) exists. Can anyone help me with the coding?