我在 C 中实现二进制搜索,我遇到了这个问题,即它不打印元素的索引号

I was implementing binary search in C and I'm facing this problem which is that its not printing the index number of the element

二进制搜索函数

#include <stdio.h>
int binarySearch(int arr[], int size, int element, int low, int high)
{
    int mid;
    while (low <= high)
    {
        if (arr[mid] == element)
        {
            return mid;
        }
        if (element < arr[mid]) //element is on the left side
        {
            high = mid - 1;
        }
        else
        {
            low = mid + 1; //element is on the right side
        }
    }
    return -1;
}

主程序从这里开始

int main()
{

    int arr[] = {1, 5, 10, 16, 24, 30, 50, 100};
    int size = sizeof(arr) / sizeof(int);
    int element = 10;
    int low = 0;
    int high = size - 1;
    int search = binarySearch(arr, size, element, low, high);

所以,我的问题是它没有打印这一行,首先,编译器没有执行程序。每当我尝试执行它时,我的电脑都会挂起[=13​​=]

    printf("The element %d was found at index %d", element, search);
    return 0;
}

你的问题是你忘记了声明initializes/definesmid,这将导致undefined behavior(之后,任何事情都可能发生到你的程序)。每次循环运行时,您还需要重新计算 mid

此外,正如下面提到的@DavidC.Rankin,您的sizeArr参数是完全没有必要的。

修改后的代码:

#include <stdio.h>
int binarySearch(int arr[], int element, int low, int high)
{
    int mid; //declare here

    while (low <= high)
    {
        mid = (low+high)/2; //recalculate here
        if (arr[mid] == element)
        {
            return mid;
        }
        else if (element < arr[mid]) //element is on the left side
        {
            high = mid - 1;
        }
        else
        {
            low = mid + 1; //element is on the right side
        }
    }
    return -1;
}

int main()
{
    int arr[] = {1, 5, 10, 16, 24, 30, 50, 100};
    int sizeArr = sizeof(arr) / sizeof(int);
    int element = 10;
    int low = 0;
    int high = sizeArr - 1;
    int searchResult = binarySearch(arr, sizeArr, element, low, high);
    printf("The element %d was found at index %d", element, searchResult);
    return 0;
}

结果:The element 10 was found at index 2

注意 searchsize 等关键字不应用作变量名。