本文介绍了在c上进行二进制搜索,而while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C上的二进制搜索代码我没有得到一些东西.

There's something that I don't get with the binary search code on C.

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

为什么while循环while(left<=right)无法编写:while(left<right)?这种变化会产生影响吗?

Why does the while loop while(left<=right) can't be written:while(left<right)? Will this change effect things?

推荐答案

int a[1] = {5};
printf("%d\n", binarySearch(a, 1, 5));

使用while(low < high),代码将显示-1(未找到-错误的答案).

With while(low < high), code prints -1 (did not find - wrong answer).

使用while(low <= high),代码将打印0(找到-正确答案).

With while(low <= high), code prints 0 (found - right answer).

这篇关于在c上进行二进制搜索,而while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 12:27