我正在尝试实现递归二进制搜索。但是,我的函数总是迭代3次,然后返回我正在搜索的列表为空。相关代码如下。 full()和insertAfter()都能正常工作。
List.cpp
#include <iostream>
#include "listA.h"
using namespace std;
List::List(int a)
{
size = a;
actual = 0;
data = new char[a];
cursor = -1;
}
int List::binarySearch(List l, int value, int imin, int imax)
{
//check if list is empty
if(imax < imin)
{
//return -1 if list is empty
return -1;
}
cout << "made it here" << endl;
//calculate midpoint of set
// problem line: int imid = imin + ((imin+imax)/2);
int imid = (imin+imax)/2;
//search for value
if(l.data[imid] > value)
{
cout << "less than"<< endl;
//value is in lower half
return binarySearch(l,value,imin,imid-1);
}
if(l.data[imid] < value)
{
cout <<" greater " << endl;
//value is in upper half
return binarySearch(l,value,imid+1,imax);
}
else
{
//value has been found
return imid;
}
}
bool List::insertAfter(char c)
{
if(!full())
{
if(actual >= cursor)
{
//shuffle values up so as to not overwrite
for(int i=cursor+1;i<=actual;i++)
{
data[i]+data[i+1];
}
}
//increment actual element count
actual++;
//add c to data after cursor
data[cursor+1]=c;
//increment cursor to new element
cursor++;
return true;
}
else
{
return false;
}
}
bool List::full()const
{
return (actual == size);
}
这是我的listA.h
class List{
public:
List(int = 10);
int binarySearch(List l, int, int, int);
bool insertAfter(char);
bool full() const;
private:
int size;
int actual;
int cursor;
char *data;
};
我的main.cpp是
int main() {
int size = 7;
char c;
List l(size);
for(int i = 0; i < size; i++) {
if(!l.insertAfter(i + '0')) {
cout << "inserting " << (char)(i + '0');
cout << "Error in insertAfter" << endl;
}
}
cout << "TEST FOR BINARYSEARCH" << endl;
//search for 2 in the list from 0->6
cout << l.binarySearch(l,2,0,6) << endl;
}
我的输出返回 //开始&lt;&lt;: 0 1 2 3 4 五 6 结束&lt;&lt; 测试BINARYSEARCH 在这里 少于 在这里 少于 在这里 少于 -1 //
所以我循环了三次然后返回-1,为什么会发生这种情况?我在哪里犯了binarySearch的错误?
答案 0 :(得分:0)
您的代码存在两个问题:
binarySearch()
方法中,您正在比较值,而不是键。这可能是您想要的,但您的列表中没有存储值2
(参见第2点)。insertAfter()
方法会在打印char
时插入0,1,2,3,4,5,6
,但实际上他们的int
值(基于您进行比较)如下:{ {1}}。我不确定这是你在这里尝试做的,但这里是48,49,50,51,52,53,54
方法的工作版本(注意binarySearch()
到char
转换):
int
以下是创建列表的代码:
int List::binarySearch(List l, int value, int imin, int imax)
{
//check if list is empty
if(imax < imin)
{
//return -1 if list is empty
return -1;
}
cout << "made it here" << endl;
//calculate midpoint of set
int imid = ((imin+imax)/2);
//search for value
if((int)(l.data[imid]-'0') > value) // <-- see the cast here
{
cout << "less than"<< endl;
//value is in lower half
return binarySearch(l,value,imin,imid-1);
}
if((int)(l.data[imid]-'0') < value) // <-- see the cast here
{
cout <<" greater " << endl;
//value is in upper half
return binarySearch(l,value,imid+1,imax);
}
if((int)(l.data[imid]-'0') == value) // <-- see the cast here (this part of your program could be simplified by removing this condition and leaving only the return)
{
//value has been found
return l.data[imid]; // <-- see the modified return here
}
}
我认为您可以从这里开始并适当地修改您的代码。