简体   繁体   English

关于C语言中的二进制搜索算法的问题

[英]Issue about Binary search algorithm in c

I am confused in understating the behavior of the code while searching for an element which does not exist in the array . 在寻找数组中不存在的元素时低估了代码的行为感到困惑。

  1. The result of the element index i am looking for is always zero while declaring it as int index; 我正在寻找的元素索引的结果在声明为int index;始终为零int index; .
  2. The result of the element index i am looking for is random number while declaring it as size_t index; 我正在寻找的元素索引的结果是随机数,同时将其声明为size_t index; what is the difference between declaring the variable index as int index; 将变量索引声明为int index;什么区别int index; and size_t; size_t; in the code below. 在下面的代码中。

The code 编码

#include <stdio.h>
#define SIZE 5
int main(void)
{
    int numbers[SIZE]={1,2,3,4,5};
    int search =0; // This variable define the required number i am searching for 
    int start = 0 ;
    int end = SIZE-1 ;
    size_t index;
    while (start <= end)
    {
        int middle = (start+end)/2;
        if  (search == numbers[middle])
        {
            index = middle;
        }
        if (search > numbers[middle])
        {
            start = middle+1 ;
        }
        else
        {
            end= middle-1 ;
        }
    }
    printf("The index of the element is %d",index);
return 0;
}

The basic problem is that index is not initialized and that it never gets assigned when you don't find what you are searching for. 基本问题是index没有初始化,当您找不到要搜索的内容时就永远不会分配index Since the printf statement accesses an uninitialized variable in that case, your code have undefined behavior, ie anything may happen - including print of all sorts of numbers. 由于在这种情况下, printf语句访问未初始化的变量,因此您的代码具有未定义的行为,即可能发生任何事情-包括打印各种数字。

The result of the element index i am looking for is always zero while declaring it as int index; 我正在寻找的元素索引的结果在声明为int索引时始终为零;

That is "just by luck" 那是“靠运气”

The result of the element index i am looking for is random number while declaring it as size_t index; 我正在寻找的元素索引的结果是随机数,同时将其声明为size_t索引;

That is also "just by luck" 那也是“靠运气”

Here are a couple of action items you can take to improve your code: 您可以采取以下几项措施来改进代码:

  1. Since this array is statically defined there is no need to include the SIZE define inside the [] . 由于此数组是静态定义的,因此无需在[]包含SIZE定义。 Declare it like this int numbers[]={1,2,3,4,5}; 这样声明int numbers[]={1,2,3,4,5}; instead of this int numbers[SIZE]={1,2,3,4,5}; 而不是此int numbers[SIZE]={1,2,3,4,5}; . Let the compiler do the math for you. 让编译器为您完成数学运算。
  2. Initialize index to some value (ie index = 0; ). index初始化为某个值(即index = 0; )。 this is the main cause of the problem and it is introducing undefined behavior to the program. 这是导致该问题的主要原因,并且正在向程序引入未定义的行为。
  3. Change the type of size_t index to int index every variable that was declared in the program is an int and the program is treating index as an int . size_t index的类型更改为int index ,在程序中声明的每个变量都是int ,并且程序将index视为int So it might as well be an int to avoid confusion. 因此,避免混淆也可能是一个int
  4. Make this an else if clause instead of just an if : 使它成为else if子句,而不仅仅是if

     else if (search > numbers[middle]) { start = middle+1 ; } 
  5. Add another case to have the program fail gracefully when the value to be searched is missing from the data set. 添加另一种情况,以便在数据集中缺少要搜索的值时使程序正常运行。 Such as, printf("Data not found: %d", search); 例如, printf("Data not found: %d", search);

The algorithm still isn't 100% and has some flaws but I will leave this up to you to figure out. 该算法仍然不是100%并有一些缺陷,但我将由您自己确定。 I hope this info helps! 希望此信息对您有所帮助!

Best Regards! 最好的祝福!

The problem is that , the value of index is not initialized. 问题在于, index的值未初始化。

initializing the variable to 0 does not solve your problem. 将变量初始化为0不能解决您的问题。 Because you are using index to return the position of the array element. 因为您使用index来返回数组元素的位置。

By initializing the index = 0 will provide he same result for the elements not present in the array as well as the for the first element to the of the array . 通过初始化index = 0将为数组中不存在的元素以及数组的第一个元素提供相同的结果。

The better way is to initialize as size_t index = -1; 更好的方法是初始化为size_t index = -1;

So that the result for the elements not present in the array would b -1. 这样,数组中不存在的元素的结果将为b -1。

Also check for the access specifier used in the printf statement, for size_t datatype. 还要检查printf语句中使用的访问说明符,以获取size_t数据类型。 It can be , 有可能 ,

printf("The index of the element is %ld",index);

You are not using correct specifier for size_t, it's not %d. 您没有为size_t使用正确的说明符,不是%d。

Try to use %zd or %ld and it'll work fine. 尝试使用%zd或%ld,它将正常工作。

Furthermore, add this after the while loop so that it doesn't show weird value of index when the element is not present in the array. 此外,在while循环之后添加此元素,以便在数组中不存在该元素时不显示索引的怪异值。

if(start>end) {
   printf("That number is not present in the array");
   return 0;
}

And move the line printf("The index of the element is %d",index); 并移动行printf("The index of the element is %d",index); under the condition if (search == numbers[middle]) . 在条件为if (search == numbers[middle]) So that you don't get "this number is not present" even if it is present in the array. 这样即使数组中存在该数字,您也不会得到“此数字不存在”的信息。 For corrected version of your code see https://code.hackerearth.com/80043dg?key=7b325b26aec0f5425b76cc3efbdc93cf 有关代码的更正版本,请参见https://code.hackerearth.com/80043dg?key=7b325b26aec0f5425b76cc3efbdc93cf

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

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