Search code examples
sortingdata-structuresbinary-search

Binary search algorithm code won't execute


    #include <stdio.h>
#include <stdlib.h>
int binary_search(int, int[], int);

int binary_search(int key,int arra[],int len){
    int low=0;
    int high=len-1;
    int mid=(low+high)/2;

    while(low<=high){
        if(arra[mid]==key){return mid;}
        else if (arra[mid]>key){high=mid-1;}

        else {low=mid+1;}
    }
     return -1;
}


int main()

{

       int arr[]={1,2,3,4,5,6,7};
    int len = sizeof(arr) / sizeof(arr[0]);
    printf("%d",len);
    binary_search(2,arr,len);
    return 0;
}

So, trying to run this and i don't get any output whatsoever, intially i had the code taking input of the array from the user but it wasn't working then either so even after simplifying it and adding the array in the code itself hasn't solved the problem. Can someone point it out?


Solution

  • You are never changing the variable mid. It is always 3 and since arr[3] > 2 (second condition), the while loop is never breaking. The low is stuck at 0 and high is stuck at 2 and it is running infinitely.

    int binary_search(int key,int arra[],int len){
        int low=0;
        int high=len-1;
        int mid=(low+high)/2;
    
        while(low<=high){            
            int mid;            
            mid=(low+high)/2;         
            if(arra[mid]==key){
                printf("Found at %d",mid);
                return 1;
            }       
            else if (arra[mid]>key){
                high=mid-1;
            }         
            else{
                low=mid+1;
            }        
        }
        return -1;
    }