简体   繁体   中英

Binary search issue in c

If i entered the 4th index element in x it runs correctly, if i entered other elements in the array it returns -1

#include<stdio.h>

int Binary_search(int A[],int n,int x)
{
    int start=0,end = n-1;
    while(start<=end)
    {
        int mid = (start+end)/2;
        if(x == A[mid])return mid;
        else if(x < A[mid]) end = mid-1; 
        else start = mid+1;
    }
    return -1;
}

int main()
{
    int A[] = {3,23,26,51,72,77,42,64};
    puts("Enter the element ");
    int x; scanf("%d",&x);
    int len = sizeof(A)/sizeof(A[0]);
    int index = Binary_search(A,len,x);
    if(index != -1) printf("Number %i is at index %i",x,index);
    else printf("It's not in the array");
}

For starters you need a sorted in the ascending order array.

This array

int A[] = {3,23,26,51,72,77,42,64};

is not entirely sorted in the ascending order. Instead you could use for example the following array

int A[] = { 3, 23, 26, 42, 51, 64, 72, 77 };

Also this else if statement

else if(x < A[mid]) end = mid-1;

is incorrect. You need to write

else if(x < A[mid]) end = mid;

And instead of

int mid = (start+end)/2;

it will be more safer to write

int mid = start + ( end - start ) / 2;

that allows to avoid an overflow of the expression start + end .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM