C 中的二进制搜索代码无法正常工作

Code for Binary search in C not working properly

我无法修复逻辑错误,因为我不知道这段代码有什么问题。每次输入,它显示 "element not found"。如果有人可以帮助我,我将不胜感激。同样在这段代码中,我假设我们将数组的大小作为奇数,如果我们决定将偶数作为大小怎么办?

#include<stdio.h>
int main(){
  int size;
  printf("Enter the number of elemets(odd number) : ");
  scanf("%d",&size);
  int arr[size];
  printf("Enter the elements in ascending order : ");
  for(int i=0;i<size;i++){
    scanf("%d",&arr[i]);
  }
  int element;
  int flag=0;
  printf("Enter element to be found : ");
  scanf("%d",&element);
  int low=0;
  int high=size-1;
  while(low<high){
    int mid=(low+high)/2;

    if(element<arr[mid]){
      high=mid-1;
    }
    else if(element>arr[mid]){
      low=mid+1;
    }
    else if(element==arr[mid]){
      printf("Element %d found at pos %d ",element,mid);
      flag=1;
      break;
    }
  }
  if(flag==0){
    printf("Element not found");
  }

  return 0;
}

编辑: 参考@TomKarzes 的更好答案

我的旧答案是:

您错过了高==低的边界情况

#include<stdio.h>
int main(){
  int size;
  printf("Enter the number of elements(odd number) : ");
  scanf("%d",&size);
  int arr[size];
  printf("Enter the elements in ascending order : ");
  for(int i=0;i<size;i++){
    scanf("%d",&arr[i]);
  }
  int element;
  int flag=0;
  printf("Enter element to be found : ");
  scanf("%d",&element);
  int low=0;
  int high=size-1;
  while(low<high){
    int mid=(low+high)/2;

    if(element<arr[mid]){
      high=mid-1;
    }
    else if(element>arr[mid]){
      low=mid+1;
    }
    else if(element==arr[mid]){
      printf("Element %d found at pos %d ",element,mid);
      flag=1;
      break;
    }
  }
  if(low==high && arr[low]==element) //Added 1 extra condition check that you missed
  {
    printf("Element %d found at pos %d ",element,low);
    flag=1;
  }
  if(flag==0){
    printf("Element not found");
  }

  return 0;
}

问题是你的 while 测试。你有:

while(low<high) {
    ...
}

low == high 如果所需值位于该位置时,这将失败。通过将测试更改为:

可以轻松解决此问题
while(low <= high) {
    ...
}

这就是修复它所需的全部内容。您不需要向 "fix it up" 添加任何特殊情况。只需确保您的数组按升序排列并且它应该可以工作。

对于数组元素数量的初学者,您 shell 使用类型 size_tint 类型的对象可以很小以容纳数组中的元素数。

循环的这个条件

int high=size-1;
while(low<high){
//...

不正确。例如,假设数组只有一个元素。在这种情况下,high 将等于 0,因此由于其初始化

而等于 left
int high=size-1;

所以循环将不会迭代,你会得到在数组中找不到输入的数字,尽管数组的第一个和单个元素实际上将等于该数字。

您需要像

这样更改条件
while ( !( high < low ) )
//...

else 语句中的 if 语句

else if(element==arr[mid]){

是多余的。你可以只写

else // if(element==arr[mid]){

如果将执行二分查找的代码放在一个单独的函数中会更好。

这是一个演示程序,展示了如何编写这样的函数。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int binary_search( const int a[], size_t n, int value )
{
    size_t left = 0, right = n;  
    int found = 0;

    while ( !found && left != right )
    {
        size_t middle = left + ( right - left ) / 2;

        if (  value < a[middle] )
        {
            right = middle;
        }
        else if ( a[middle] < value )
        {
            left = middle + 1;
        }
        else
        {
            found = 1;
        }
    }

    return found;
}

int cmp( const void *a, const void *b )
{
    int left  = *( const int * )a;
    int right = *( const int * )b;

    return ( right < left ) - ( left < right );
}

int main(void) 
{
    const size_t N = 15;

    srand( ( unsigned int )time( NULL ) );

    for ( size_t i = 0; i < N; i++ )
    {
        size_t n = rand() % N + 1;

        int a[n];

        for ( size_t j = 0; j < n; j++ ) a[j] = rand() % N;

        qsort( a, n, sizeof( int ), cmp );

        for ( size_t j = 0; j < n; j++ )
        {
            printf( "%d ", a[j] );
        }
        putchar( '\n' );

        int value = rand() % N;

        printf( "The value %d is %sfound in the array\n",
                value, binary_search( a, n, value ) == 1 ? "" : "not " );
    }

    return 0;
}

它的输出可能如下所示

0 2 2 3 4 5 7 7 8 9 10 12 13 13 
The value 5 is found in the array
4 8 12 
The value 10 is not found in the array
1 2 6 8 8 8 9 9 9 12 12 13 
The value 10 is not found in the array
2 3 5 5 7 7 7 9 10 14 
The value 11 is not found in the array
0 1 1 5 6 10 11 13 13 13 
The value 7 is not found in the array
0 3 3 3 4 8 8 10 11 12 14 14 14 14 
The value 3 is found in the array
0 5 5 10 11 11 12 13 13 14 14 
The value 12 is found in the array
3 4 5 7 10 13 14 14 14 
The value 14 is found in the array
0 3 3 7 
The value 2 is not found in the array
1 6 9 
The value 10 is not found in the array
2 2 3 3 4 4 4 5 5 6 8 8 9 13 13 
The value 11 is not found in the array
11 11 13 
The value 11 is found in the array
0 0 0 1 2 5 5 5 7 7 8 9 12 12 14 
The value 6 is not found in the array
8 8 13 
The value 1 is not found in the array
2 2 4 4 5 9 9 10 12 12 13 13 14 14 
The value 14 is found in the array