All submissions

Binary Search in Sorted Array

Code

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

int binary_search(uint8_t *arr, uint8_t n, uint8_t key) {
    
    // Corner case for just one element
    if (n == 1) {
        if (arr[0] == key) {
            return 0;
        } else {
            return -1;
        }
    }

    // Ceiling operator
    int idx = (n+2-1)/2;

    while (idx >= 0 && idx <= (n-1)) {
        int delta = (n-idx+2-1)/2;
        if (arr[idx] == key) {
            return idx;
        } else if (arr[idx] > key) {
            idx -= delta;
        } else if (arr[idx] < key) {
            idx += delta;
        } 
    }
    
    return -1;
}

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;
}

Solving Approach

 

 

 

Loading...

Input

6 5 10 15 20 25 30 20

Expected Output

3