Binary search using C language is not possible

Asked 2 years ago, Updated 2 years ago, 93 views

int arr[5] = { 0 };

int main() { int n = 0, q = 0, x = 0; int a = 0; int r = 0, l = 0; int i = 4;

n = 5;
r = (n - 1);
q = 10;
for (int j = (n - 1); j>(-1); j--)
{
    arr[j] = 10 + 10 * i;
    printf("arr[%d] = %d\n", j, arr[j]);
    i--;
}

for (int k = 0; k<q; k++)
{
    x = 10 + 10 * k;
    printf("x=%d  ", x);

    while (r >= l)
    {
        int m = ((l + r) / 2);
        if (x == arr[m])
        {
            a = 1;
            break;
        }
        if (x < arr[m])
            r = m - 1;
        else
            l = m + 1;
    }

    if (a == 1)
        printf("YES\n");
    else
        printf("NO\n");

    a = 0;
}

return 0;

}

If you use the following source code, you will get NO from 30Can I know the reason?

binary search

2022-09-21 21:51

1 Answers

The second for loop letter r and l are not initialized.

#include <stdio.h>

int arr[5] = { 0 };

int main() {
    int n = 5, q = 10;
    int a = 0;

    for(int i=0; i<n; i++)
    {
        arr[i] = 10 + 10 * i;
    }

    for (int k = 0; k < q; k++)
    {
        int = n-1, l = 0; // initialize r, l for statement first.
        int x = 10 + 10 * k;
        printf("x=%d  ", x);

        while (r >= l)
        {
            int m = ((l + r) / 2);
            if (x == arr[m])
            {
                a = 1;
                break;
            }
            if (x < arr[m])
                r = m;
            else
                l = m + 1;
        }

        if (a == 1)
            printf("YES\n");
        else
            printf("NO\n");

        a = 0;
    }

    return 0;

}


2022-09-21 21:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.