c++ - 二进制搜索 - 代码编译和运行后不显示输出

标签 c++ c++11 search binary-search

我刚刚在类里面学习二分查找,下面的代码只是一个示例,因为我正试图更好地理解它。所以话虽如此,这段代码正在编译但没有显示任何输出,并且由于我缺乏二进制搜索的知识,我不知道为什么没有任何输出。有人可以指出写得很好的教程的方向吗?或者帮助指出代码有什么问题。

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <vector>
#include <algorithm>

using namespace std;
int SIZE = 10;

int main()
{
    int thisArray[] = { 99,86,44,55,78,63,0,32,11 };
    int num = 0;

    int n = 0;

    int first;
    int last;
    int middle;
    first = 0;
    last = n - 1;
    middle = (first + last) / 2;
    cout << "Enter the total number of elements\n";
    cin >> n;

    cout << "Entered " << n << "number.\n";

    for (int i = 0; i < n; i++) {
        cin >> thisArray[i];
    }

    cout << "Enter a number to find.\n";
    cin >> num;

    while (first <= last) {
        if (thisArray[middle] < num) {
            first = middle + 1;
        }
        else if (thisArray[middle] == num ) {
            cout << num << " found at location " << middle + 1 << "\n";
            break;
        }
        else {
            last = middle - 1;
        }
        middle = (first + last) / 2;
    }


    return 0;
}

编辑:

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <vector>
#include <algorithm>

using namespace std;
int SIZE = 10;

int main()
{
    //this is my binary search
    int thisArray[10] = { 0,11,32,44,55,63,78,86,99 };
    int i = 0; //index of the array
    int n = 0; //variable of number that will be looked for
    int first = 0;
    int last = SIZE - 1;
    int middle;
    int pos = -1;
    bool found = false;
    int count = 0;
    while (found) {

        cout << "Enter a number to look for.\n";
        cin >> n;


        while (first <= last) {
            middle = first + last / 2;
            if (thisArray[middle] == n) {

                pos = middle;
                cout << "item found at " << middle + 1 << "\n";

                exit(0);
            }
            else if (thisArray[middle] > n) {
                last = middle - 1;
            }
            else {
                first = middle + 1;
            }//endif
        }//end while
    }//end big while
    //if()


    return 0;
}

我明白了。感谢大家的帮助!

最佳答案

它没有输出任何东西,因为 first == 0last == -1 .因此 first <= last永远不会为真,并且永远不会执行循环体。

关于c++ - 二进制搜索 - 代码编译和运行后不显示输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47215459/

相关文章:

c++ - 重建后 Win32 Paint Text 仍然存在

C++:函数在输出前自动使用50减去/增加输入数

c++ - TR2 会在 C++17 中发布吗?

search - 如何在vim中使用awk进行搜索和替换?

javascript检查元素是否包含数组的某些部分

c++ - 如何在 C++11 的模板中只接受数字和字符串?

c++ - 如果我默认复制构造函数,是否会生成 move 构造函数和 move 赋值?

c++ - 固定大小的字符串类型容器

c++ - 使用 std::function 中函数的类型来声明该类型的多个函数

python - 在 for 循环中搜索字符串,而不在循环中单独引用每个字符串