【问题标题】:Binary Search Results being very inconsistent二进制搜索结果非常不一致
【发布时间】:2021-04-27 15:07:04
【问题描述】:

在学校进行编码练习,我们必须利用二分搜索来查找数组中值的位置。输出应生成索引位置。

在测试它时,它非常“碰碰运气”。有时它会说当一个值存在时,其他时候当一个值明显存在时它会提出“元素不存在于数组中”。正在努力排除这种不一致的根源。

任何帮助/提示/建议将不胜感激。

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

#define SIZE 10

int binarySearch(int array[], int starting, int ending, int searchKey)
{

if (ending >= starting)
{       
        int mid = starting + (ending - starting)/2;
        if (array[mid] == searchKey) return mid;
        if (array[mid] > searchKey) return binarySearch(array, starting, mid-1, searchKey);
        return binarySearch(array, mid+1, ending, searchKey);
}
return -1;
}

int main(void)
{
    int array[10],i;
    int searchKey;

    srand(time(NULL));
    for (i=0; i<10; i++)
    array[i]=rand()%100;

    printf("Array before sorting \n");
    for (i=0; i<10; i++)
    printf("%d \n", array[i]);
   
    printf("Enter a number to search\n");
    scanf("%d", &searchKey);

    int result = binarySearch(array, 0, SIZE-1, searchKey);
    (result == -1)? 

    //Displaying the results to the user
    printf("Element is not present in array")
    : printf("Element is present at index %d", result+1);
    
    return 0;
}

【问题讨论】:

  • 请添加“错过”的示例。并修复代码缩进。
  • 输入是否排序?这是二进制搜索工作的必要条件。
  • 请不要使用三元条件表达式而不是普通的if else 语句。它会让你的代码更难阅读和理解。
  • 你在哪里排序你的数组?
  • 确保数组已排序,因为二进制搜索适用于已排序的数组。

标签: c binary-search


【解决方案1】:

二分查找需要对数组进行排序。

参见例如https://en.wikipedia.org/wiki/Binary_search_algorithm#:~:text=Binary%20search%20works%20on%20sorted,lower%20half%20of%20the%20array.

上面写着:

在计算机科学中,二分搜索,也称为 ....,是一种搜索算法,用于查找目标值在排序数组中的位置。

您可以通过以下方式生成数组:

for (i=0; i<10; i++)
    array[i]=rand()%100;

所以它显然不是一个排序数组。因此,二分搜索将起作用。

您可以在数组上使用qsort 对其进行排序。如果您不允许更改数组,则需要另一种搜索算法而不是二分搜索。

【讨论】:

    【解决方案2】:

    在应用二分搜索之前,您的数组需要按升序/降序排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多