Home > database >  Binary search array showing -1 as result
Binary search array showing -1 as result

Time:11-20

#include<stdio.h>
int binary_search(int arr[], int size ,int element){
    int low, mid, high; 
    low=0;
    high=size-1;
    //start of search
    while(low<=high)
    {
        mid = (low   high)/2;
        if(arr[mid] == element){
        return mid;
        }
        if(arr[mid]<element){
        low= mid 1;
        }
        else{
        high = mid-1;
        }
    }
    //end of search
    return -1;
}
int main(){
    int arr[20]={1,20,31,44,54,68,70,85};
    int size= sizeof(arr)/sizeof(int);
    int element=44;
    int Si= binary_search(arr,size,element);
    printf("Element was found at index: %d \n",Si);
    return 0;

} 

why does my code returns -1 everytime . I tried changing arr[20] to arr[] in main function and it started working fine. Can someone explain me the reason behind this?

CodePudding user response:

This line of code creates an integer array of length 20, with all the elements after 85 being initialized to zeros.

int arr[20]={1,20,31,44,54,68,70,85};

The sizeof operator gives the size, in bytes, of the integer array arr of length 20, which causes the value of size to be 20. This causes the binary search algorithm to fail, as it does not deal with arrays that are not sorted.

  • Related