How to find the closest value in the search table?

I have a simple one-dimensional array of integer values ​​representing a physical set of part values ​​that I have to work with. Then I mathematically calculate and optimally evaluate.

How can I write an efficient search algorithm that finds the least difference from my ideal value in an array?

The array is predefined and constant, so it can be sorted, but I need to.

Example Search Array:

100, 152, 256, 282, 300

Finding the ideal value of 125 will find 100 in the array, while 127 will find 152.

The actual array of queries will contain about 250 elements and will never change.

+5
source share
5 answers

+3

, , , , .

- , .

n [] = {1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
: 2,
1: = 10, = 0, = 5
2: = 5, = 0, = 2
3: = 2, = 0, med = 1 . 1.

: 3 ( ),
1: = 10, = 0, = 5
2: = 5, = 0, = 2
3: = 2, = 0, = 1
4: = 1, = 0, = + 1, . , med = 1.

, ...

public static <T> int binarySearch(List<T> list, T key, Comparator<T> compare) {
                int low, high, med, c;
                T temp;
                high = list.size();
                low = 0;
                med = (high + low) / 2;

                while (high != low+1) {
                    temp = list.get(med);
                    c = compare.compare(temp, key);

                    if (c == 0) {
                        return med;
                    } else if (c < 0){
                        low = med;
                    }else{
                        high = med;
                    }

                    med = (high + low) / 2;
                }

                return med; 
            }

    /** ------------------------ Example -------------------- **/

    public static void main(String[] args) {
                List<Integer> nos = new ArrayList<Integer>();
                nos.addAll(Arrays.asList(new Integer[]{1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20}));

                search(nos, 2); // Output Search:2  Key:1   Value:2
                search(nos, 3); // Output Search:3  Key:1   Value:2

                search(nos, 10); // Output Search:10    Key:5   Value:10
                search(nos, 11); // Output Search:11    Key:5   Value:10
            }

    public static void search(List<Integer> nos, int search){
                int key = binarySearch(nos, search, new IntComparator());
                System.out.println("Search:"+search+"\tKey:"+key+"\tValue:"+nos.get(key));
            }

            public static class IntComparator implements Comparator<Integer>{
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o1.compareTo(o2);
                }
            }
+3

:

int binary_search(int A[], int key, int imin, int imax)
{
  // continue searching while [imin,imax] is not empty
  while (imax >= imin)
    {
      // calculate the midpoint for roughly equal partition
      int imid = midpoint(imin, imax);
      if(A[imid] == key)
        // key found at index imid
        return imid; 
      // determine which subarray to search
      else if (A[imid] < key)
        // change min index to search upper subarray
        imin = imid + 1;
      else         
        // change max index to search lower subarray
        imax = imid - 1;
    }
  // key was not found
  return KEY_NOT_FOUND;
}

, , , imax < imin.

. imax imin ( , ). , imax < imin . , , , A[imax] < key < A[imin] :

if imax <= 0 return 0
if imin >= A.count - 1 return A.count - 1
if (key - A[imax]) < (A[imin] - key) return imax
return imin
+1

abs (reference-array_value [i]), O (N). .

0

Python, ( Python) O(n):

table = (100, 152, 256, 282, 300)
value = 125

lookup_dict = dict([(abs(value-x),x) for x in table])
closest_val = ldict[min(ldict.keys())]

, , O(log_n):

import bisect
'''Returns the closest entry in the sorted list 'sorted' to 'value'
'''
def find_closest(sorted, value):
    if (value <= sorted[0]):
        return sorted[0]
    if (value >= sorted[-1]):
        return sorted[-1]
    insertpos = bisect.bisect(sorted, value)
    if (abs(sorted[insertpos-1] - value) <= abs(sorted[insertpos] - value)):
        return sorted[insertpos-1]
    else:
        return sorted[insertpos]
0

All Articles