0

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?

Xiaojun Chen
  • 1,222
  • 2
  • 12
  • 21
  • 1
    Read about binary search. PS, there's a method in Arrays that does what you need - `public static int binarySearch(double[] a, double key)`. – Eran Nov 26 '15 at 10:36
  • Possible duplicate of [binary search on array of integer in java](http://stackoverflow.com/questions/28099177/binary-search-on-array-of-integer-in-java) – Perfect28 Nov 26 '15 at 10:37
  • You can use dichotomic search since the elements are sorted : https://en.wikipedia.org/wiki/Dichotomic_search – Patrick Nov 26 '15 at 10:37
  • 1
    As a general advice for solving these kinds of problems: if you're told to find a logarithmic algorithm, you can be certain about two things: 1. The solution will be recursive. 2. In every recursive step the algorithm will split up the search space into a number of equal parts and discard some of them. – biziclop Nov 26 '15 at 10:38

1 Answers1

1

Your array is sorted, this means you can use binary search. I have nothing to add to this answer and will not provide you ready code, because it is your responsibility. The main idea is that you examine middle element of the array and then determine in which direction you should move: first or second half of an array and so on.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241