107. Binary Search in Sorted Array

Back To All Submissions
Previous Submission
Next Submission

Code

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

int binary_search(uint8_t *arr, uint8_t n, uint8_t key) {
    // Binary search:
    // 1. Find middle value
    // 2. Check if target value (key) is higher/lower
    // 3. Find next new middle value (higher/lower)
    // 4. Repeat until value = target value
    int middle_index=n/2;
    for(int i=0;i<n;i++){
        if(arr[middle_index] == key){
            return middle_index;
        }
        else if(arr[middle_index] < key){ //If middle val < key (find new higher middle)
            middle_index = n-middle_index/2;
        }
        else { //If middle val > key (find new lower middle)
            middle_index = middle_index/2;
        }
    }
    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

 

 

 

Was this helpful?
Upvote
Downvote