我刚刚在课堂上学习二进制搜索,下面的代码只是一个例子,因为我试图更好地理解它。所以说这个代码是编译但不显示任何输出,因为我缺乏二进制搜索的知识,我不知道为什么没有任何输出。有人可以指出真正写好的教程的方向吗?或者帮助表明代码有什么问题。
#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;
}
我明白了。感谢大家的帮助!
答案 0 :(得分:2)
由于和
first == 0
,它没有输出任何内容。因此last == -1
永远不会成立,循环体永远不会被执行。
答案 1 :(得分:0)
答案 2 :(得分:0)
简单
将last = n - 1;
更改为last = SIZE - 1;
或在您接受last = n - 1;
n
此外,阵列需要排序!
答案 3 :(得分:0)
想出来。现在虽然代码是一个例子,我发现for循环对我来说不正常,所以我摆脱它。对于迭代,我实现了一个do-while循环。但是,代码现在正常工作。
#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;
do {
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;
exit(0);
}
else if (thisArray[middle] > n) {
last = middle - 1;
}
else {
first = middle + 1;
}//endif
}//end while
} while (found = true);
return 0;
}