c - 只有两次比较的迭代二分查找?

标签 c binary-search

调整迭代二进制搜索代码,使其只使用两次比较而不是三个(在 主 while 循环)。 *注:三个比较在while循环中,两个if语句 在循环内。

#include <stdio.h>

int ItBinarySearch(int arr[], int len, int target) {

    int first = 0;
    int last = len-1;

    while (first <= last){
        // Assert: array is sorted
        int mid = (first+last) / 2;

        if (target == arr[mid])
            return 1;

        if (target < arr[mid])
            last = mid-1;

        else first = mid+1;
    }
    return 0;
}

int main(void){
    int arr[6]={0,1,2,3,4,5};
    int len=sizeof(arr)/sizeof(arr[0]);
    int target = 4;
    printf("%d\n",ItBinarySearch(arr,len,target));
}

最佳答案

提示:尝试将其中一个 if/else 语句移出循环。哪个 if/else 最有可能成为算法在语句之外仍然有效的候选者?

关于c - 只有两次比较的迭代二分查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49060796/

相关文章:

java - 如何执行文本文件的二进制搜索

java - 二分查找给出了错误的输出 Java

c - 在 C system() 函数中隐藏控制台,Win

c - JACK 语言的 Lexer 中的段错误

c - C中的二进制搜索中的段错误

java - 循环内二分查找的时间复杂度

python - pandas 中非唯一索引的性能影响是什么?

C 宏编译器警告

android - fopen() 不重置文件

c - 未使用计算值