Binary Search in Sorted Array

Code

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

// 100 150 200 250
// 250

int binary_search(uint8_t *arr, uint8_t n, uint8_t key) {
    // maximum we will get the element by (n+1)/2 iterations, be it even or odd
    // in the starting, set i as n/2
    int i=n/2;
    for(int x=0;x<((n+1)/2);x++) {
        if(key==arr[i])
            return i;
        else if(key>arr[i]) {
            i+=(n-i)/2;
        }
        else if(key<arr[i]) {
            i/=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

 

 

 

Upvote
Downvote
Loading...

Input

6 5 10 15 20 25 30 20

Expected Output

3