C ++二进制搜索无法正常工作-查找元素不在数组中

为了某物

我正在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;
}
abhishek_naik

您正在调用未定义的行为,因为您的for循环条件为<=arraySize将其更改为<arraySize进行此更改后,该代码可完美地用于示例输入。

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

现场演示

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章