Binary Search on Sorted Lookup Table

Easy C Optimization Asked at Apple
Solve this problem

A calibration table maps ADC codes to temperatures and is sorted by code. Find the index of the largest entry less than or equal to the query, for interpolation.

Constraints

  • Signature: `int lut_find(const uint16_t *table, int len, uint16_t query)`.
  • Return -1 when the query is below table[0].
  • Return len-1 when the query is at or above the last entry.
  • Must be O(log n).
  • Must not overflow when computing the midpoint.
  • The table may contain duplicates; return the highest matching index.
Starter codeC
1#include <stdint.h>2 3int lut_find(const uint16_t *table, int len, uint16_t query) {4    // TODO5    return -1;6}