Binary Search in Sorted Array

Code

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

int binary_search(uint8_t *arr, uint8_t n, uint8_t key) {
    size_t higher = n;
    size_t lower = 0;
    while(1){
        size_t pos = (higher + lower) / 2;
        uint8_t found = *(arr+(pos));
        // printf("H: %d, L: %d, P: %d, Found: %d, Key: %d\n", higher, lower, pos, found, key);
        if (found == key){
            return pos;
        }
        if (found > key) {
            higher = pos-1;
            if (pos == 0){
                return -1;
            }
        } else {
            lower = pos+1;
            if (pos == (n-1)){
                return -1;
            }
        }
        if ((higher == pos) & (lower == pos)){
            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

 

 

 

Upvote
Downvote
Loading...

Input

6 5 10 15 20 25 30 20

Expected Output

3