c - 二分查找代码行

标签 c binary-search

我一直在努力学习二分查找的工作原理,所以我搜索了一段代码并试图理解每一行的作用。我不明白这一行。带有“return -1”的行。我不明白那是什么意思。有人可以解释那行代码中发生了什么吗?

 #include<stdio.h>

int binarySearch(int array[], int size, int searchValue){
int low = 0;
int high = size - 1;

while(low<=high){// is the array exhausted?
    int mid = (low + high) / 2; //If not, find the middle index

    if(searchValue == array[mid]){
        return mid;
    }
    else if(searchValue > array[mid]){
        low = mid + 1;
    }
    else{
        high = mid - 1;
    }
}
return -1;
}

int main(){
int array[] = {1,2,3,4,5,6,7};
int searchNum;

printf("Enter an integer:");
scanf("%d", &searchNum);

int result = binarySearch(array,7,searchNum);

if(result>=0){
    printf("Found!");
}
else{
    printf("Not found!");
}
getch();
}

最佳答案

二分查找是对数组进行的,数组的位置是从0开始的,所以如果返回-1,则表示该位置不在数组中或无法定位。

关于c - 二分查找代码行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46947928/

相关文章:

java - 如果数组未排序,则 binarySearch 返回一个随机索引;返回索引背后的逻辑是什么?

c - 将 C 程序安装到另一台机器上,无需共享代码

java - 使用 Java8 Streams API 实现二分查找

php - PHP 中的正则表达式二进制模式搜索

c - 鼠标坐标

algorithm - 使用搜索和排序的不相交集

java - Codility 钉板

c - 将结构传递给 pthread_create,强制转换后未定义值?

逗号分隔值

c - 如何使用 opencv 映射相机图像来创建现场 Playground 镜子?