递归二进制搜索返回正确的目标,但在数组的中间索引处

问题描述 投票:0回答:1

[学习如何创建二进制搜索,但遇到了问题。

我不熟悉递归,甚至不确定我是否正确执行了此操作,但是它返回的是正确的目标,但始终在中间索引处。

我不知道程序如何在索引5不保持20的情况下在索引5输出值20。

任何批评都欢迎!!

int main(void)
{
    int const numbers[10] = {1,3,4,7,13, 14, 17, 18, 20, 23};
    int const target = 20;
    int result = 0;
    result = binarySearch(&numbers, 1, 10, target);
    if (result != -1)
    {
        printf("Element is found in array in index: %d, and holds value: %d\n", result, numbers[result]);
    }
    else
    {
        printf("Element is not found in array\n");
    }
}

int binarySearch(int* arr, int low, int high, int x)
{
    if (high >= low)
    {
        int mid = low + (high - low) / 2;
        if (arr[mid] = x)
        {
            return mid;
        }
        else if (arr[mid] > x)
        {
            return binarySearch(arr, low, mid - 1, x);
        }
        else if (arr[mid] < x)
        {
            return binarySearch(arr, mid + 1 , high, x);
        }   
    }
    else
    {
        return -1;
    }
}

输出

Element is found in array in index: 5, and holds a value of: 20
c algorithm recursion search binary
1个回答
0
投票

这是您的代码有什么问题:

if (arr[mid] = x)

应该是:

if (arr[mid] == x)
© www.soinside.com 2019 - 2024. All rights reserved.