Shay
Shay

Reputation: 29

Facing problems in binary search in c

#include <stdio.h>
int bsearch(int ar[],int n,int key)
{
    int s=0;
    int e=n-1;
    
    while(s<=e){
        int mid=(e+s)/2;
        if(mid==key){
            return mid;
        }
        else if(key<mid){
            e=mid-1;
        }
        else if(key>mid){
            s=mid+1;
        }
    }
    return -1;
}

I made the function for the binary search

int main()
{
    int n,key;
    int ar[n];
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        printf("ar[%d]= ",i);
        scanf("%d",&ar[i]);
        
    }
    printf("Enter key>> \n");
    scanf("%d",&key);
    printf("%d is the index",bsearch(ar,n,key));
    return 0;
}

Then I inputted an sorted array but with repetitions. Shown in the following image.

input in terminal

The output is coming as 3 is the index. But it should as come as 6 is the index.

Upvotes: 0

Views: 64

Answers (1)

Ratery
Ratery

Reputation: 2917

mid is an index of element, not a value. So, I have corrected your function:

#include <stdio.h>
int bsearch(int ar[], int n, int key)
{
    int s=0;
    int e=n-1;
    
    while(s <= e){
        int mid = (e + s) / 2;
        if(key == ar[mid]) {
            return mid;
        }
        else if(key < ar[mid]) {
            e = mid-1;
        }
        else if(key > ar[mid]) {
            s = mid+1;
        }
    }
    return -1;
}

Upvotes: 3

Related Questions