【问题标题】:C++ Binary Search Not Working Correctly - Finds Element Not in ArrayC++ 二进制搜索无法正常工作 - 查找不在数组中的元素
【发布时间】:2016-09-10 15:52:25
【问题描述】:

我在 C++ 中运行二进制搜索算法,但它给了我虚假的结果。例如,搜索值 21 会给我一个

“找到值”

消息,但我的数组仅包含从 0 到 20 的数字。

非常感谢任何帮助。

#include <iostream>
#include <iomanip>
using namespace std;

int binarySearch(const int [], int, int, int, int ); // function prototype

int main()
{
    const int arraySize = 10;
    int arr[ arraySize ];
    int key;

    for( int i = 0; i <= arraySize; i++)  // generate data for array
       arr[i] = 2*i;

    cout << "The array being searched is: " << endl;

    for (int j = 0; j<=arraySize; j++)  // print subscript index of the array
    {
    cout << setw(5) << j << " ";
    }

    cout << endl;

    for (int z = 0; z<=arraySize; z++) // print elements of the array below index
    {
     cout << setw(5) << arr[z] << " ";
    }

    cout << "\n" <<"Enter value you want to search in array " << endl;
    cin >> key;

    int result = binarySearch(arr, key, 0, arraySize, arraySize); // function call

    if (result == 1)                  // print result of search
    cout << "Key is found " << endl;
    else
    cout << "Key not found " << endl;

    return 0;
} // end main function

int binarySearch(const int a[], int searchKey, int low, int high, int length)
{
    int middle;

    while (low <= high){

        middle = (low + high) / 2;

        if (searchKey == a[middle]) // search value found in the array, we have a match
        {
        return 1;
        break;
        }

        else
        {
        if( searchKey < a[middle] )  // if search value less than middle element
            high = middle - 1;      // set a new high element
        else
            low = middle + 1;       // otherwise search high end of the array
        }
    }
return -1;
}

【问题讨论】:

  • 当您使用调试器单步执行代码时,一次一行,您的调试器告诉您代码产生错误结果的原因是什么?
  • 你的数组排序了吗?
  • 我逐行浏览并看不到问题,但我认为答案是下面的 CodingBatman 的答案。

标签: c++ algorithm search binary


【解决方案1】:

您正在调用undefined behavior,因为您的for 循环条件是&lt;=arraySize。将其更改为&lt;arraySize。进行此更改后,代码可以完美地用于示例输入。

通过编写int arr[ arraySize ];,您正在创建一个包含10 个元素的数组(即,从09),而在for 循环中,您从0 开始并移动到10

Live Demo

【讨论】:

  • 谢谢,问题如你所说。还必须调整函数调用。根据您所说,调用中的第三个参数应该是“arraySize - 1”而不是“arraySize”。
猜你喜欢
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
  • 2022-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多