Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Binary search array showing -1 as result

#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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading