83. Binary Search in Sorted Array

#include <stdio.h>
#include <stdint.h>

// Iterative binary search for sorted array
int binary_search(uint8_t *arr, uint8_t n, uint8_t key) {
    int low = 0;
    int high = n - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == key) {
            return mid; // Found the key
        } else if (arr[mid] < key) {
            low = mid + 1; // Search right half
        } else {
            high = mid - 1; // Search left half
        }
    }

    return -1; // Key not found
}

int main() {
    uint8_t n, key;
    scanf("%hhu", &n);
    uint8_t arr[100];

    for (uint8_t i = 0; i < n; i++) {
        scanf("%hhu", &arr[i]);
    }
    scanf("%hhu", &key);

    int index = binary_search(arr, n, key);
    printf("%d", index);
    return 0;
}

What’s the goal?

Binary search cuts the array in half each time. It’s efficient (O(log n)) and requires the array to be sorted.

Why it matters in firmware?

  • Frequently used in lookup tables (LUT), e.g., calibration, sensor ranges
  • Minimizes memory access cycles in performance-critical applications
  • Firmware-safe when depth and array bounds are controlled

Solution Logic

  • Start with full range (low = 0, high = n-1)
  • Calculate mid-point
  • Narrow down based on comparison with key
  • Repeat until found or exhausted
     
Loading...

Input

6 5 10 15 20 25 30 20

Expected Output

3