Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of Binary Search of a Sorted Array in C

I've written the following program to implement Binary Search of a sorted array:

    int flag=0;

    void binarysearch(int x, int a[], int m, int n)
    {
        int middle=(m+n)/2;
        if(a[middle]==x)
        {
            printf("%d has been found at postion %d!\n", x, middle+1);
            flag=1;
        }
        else
        if(x > a[middle])
            binarysearch(x, a, middle, n);
        else
        if(x < a[middle])
            binarysearch(x, a, m, middle);
    }

    main()
    {
        int i, size, x;
        int a[100];
        printf("Enter the size of the list : ");
        scanf("%d", &size);
        printf("Enter the list items in ascending order : \n");
        for (i=0; i<size; i++)
        scanf("%d", &a[i]);
        printf("Enter the element to be found : ");
        scanf("%d", &x);
        binarysearch(x, a, 0, size-1);
        if(flag != 1)
        printf("%d has not been found in the list!", x);
    }

The problem with this program is, the function binarysearch recursively calls itself over and over again if an attempt is made to search an item that is not in the list. Therefore, the flag variable becomes completely pointless.

Is there a possibility of the program being able to tell the user if he is attempting to perform such a search (of something that's not in the array)?

I am assuming it is not possible as it is a basic flaw in the binary search algorithm. Please enlighten me.

like image 784
Vikram Avatar asked Dec 01 '25 15:12

Vikram


1 Answers

Check for m == n at the beginning.

if(m == n)
{
    if(a[n] == x) { printf("found\n"); }

    return;
}

If there's no x, you keep on calling yourself with middle == n and middle == m.

like image 155
Viktor Latypov Avatar answered Dec 03 '25 07:12

Viktor Latypov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!