All submissions

Binary Search in Sorted Array

Code

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

int binary_search(uint8_t *a, uint8_t n, uint8_t key) 
{
    int left=0;
    int right=n-1;
    int mid;
    
    while(left<=right)
    {
        mid=(left+right)/2; 
        if(key>a[mid]) //if the searching element is greater than mid, shift left index=mid+1.
         left=mid+1;
        else if(a[mid]>key) //if the searching element is lesser than mid, shift right index=mid-1;
          right=mid-1;
        else 
           return mid;
}
    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