简体   繁体   English

二分查找在 C 中不起作用

[英]binary search doesn't work in C

I have the following binary search algorithmn:我有以下二分搜索算法:

int search_binary(int* tab,int size, int a)
{
    int lower=0,upper=size-1,middle=(lower + upper)/2;
    while(lower < upper)
    {
        if(tab[middle] == a)
            break;
        else if(tab[middle] < a)
        {
            upper = middle - 1;
            middle = (lower + upper)/2;
        } else {
            lower = middle + 1;
            middle = (lower + upper)/2;
        }

    }

    if(tab[middle] == a)
        return middle;
    else
        return -1;

}

It either return -1 if I insert a number, that exists or it returns the wrong index.如果我插入一个存在的数字,它要么返回 -1,要么返回错误的索引。

exampledata:示例数据:

table: 2 2 4 5 7 7 8 8 8 9表:2 2 4 5 7 7 8 8 8 9

searched number: 7搜索次数:7

result: The index is: 4结果:指数为:4

table: 1 2 3 4 6 6 6 7 8 9表:1 2 3 4 6 6 6 7 8 9

searched number: 4搜索数量:4

result: The index is: -1结果:索引为:-1

else if(tab[middle] < a)
    {
        upper = middle - 1;
        middle = (lower + upper)/2;
    }

From here it seems that you expect the array to be ordered in decreasing order.从这里看来,您希望数组按降序排列。 In fact, giving it an array ordered that way, it works for me.事实上,给它一个这样排序的数组,它对我有用。

just change the if to:只需将if更改为:

if(tab[middle] > a)

To have it working for an array ordered in increasing order让它为按递增顺序排列的数组工作

A slight change in you loop in function -你的循环功能略有变化 -

int search_binary(int* tab,int size, int a)
{
   int lower=0,upper=size-1,middle=(lower + upper)/2;
   while(lower < upper)
  {
    if(tab[middle] == a){               // if found 
        return middle;                  // return index 
      }
    else if(tab[middle] < a)            // if a is greater 
    {
        lower= middle ;          //lower is updated to middle,search in part above middle 
        middle = (lower + upper)/2;
    } else {
        upper = middle - 1;     //else upper is updated search in part lower than middle
        middle = (lower + upper)/2;
    }

  }
 return -1;
}

What mistake your loop was doing that when tab[middle]<a then due to updation of upper it would search number in part 0 to middle -1 whereas , number was at higher index.I have updated your code with correct changes in vairables.tab[middle]<a时,你的循环犯了什么错误,然后由于upper更新,它会在第0 to middle -1部分0 to middle -1搜索数字,而数字处于更高的索引。我已经用变量中的正确更改更新了你的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM