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) {
    // Your logic here
    int median = n/2;
    int low=0;
    int high = n-1;

 while (  low <= high) { //median < n && median >= 0 can give wrong values if low =5 and high =4 we get stuck and it is corner case  that can happen check case 2 as an example
    if ( arr[median] > key ){ 
        high = median -1;
        median = (low + high )/2;
    }
    else if (arr[median] < key ){
        low = median+1;
        median = (high + low )/2;
  }
  else 
        return median;
}
    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