C++ C++;二进制搜索关键字错误
在那里。我正在尝试使用二进制搜索来计算文件中的关键字。但在某些情况下,函数返回正确的索引,而在其他情况下,它无法获取索引。我不知道这是为什么。这是我的密码:C++ C++;二进制搜索关键字错误,c++,binary-search,C++,Binary Search,在那里。我正在尝试使用二进制搜索来计算文件中的关键字。但在某些情况下,函数返回正确的索引,而在其他情况下,它无法获取索引。我不知道这是为什么。这是我的密码: GlobalsDefine.h #pragma once #define MAXLEN 10 #define TOTAL 32 #define HASHLEN 41 extern const char* KeyWords[TOTAL]; BiSearch.h #ifndef BISEARCH_H #define B
GlobalsDefine.h
#pragma once
#define MAXLEN 10
#define TOTAL 32
#define HASHLEN 41
extern const char* KeyWords[TOTAL];
BiSearch.h
#ifndef BISEARCH_H
#define BISEARCH_H
#include <iostream>
#include <cstring>
#include <iomanip>
#include "GlobalsDefine.h"
using namespace std;
class SeqWords
{
public:
char keyword[MAXLEN];
int length;
int count;
};
int BiSearch(char* des, const char** src, int begin, int last);
void initKeyWords(SeqWords* SW);
#endif // BISEARCH_H
二进制搜索需要对数组进行排序,这不是您的情况
对于排序输入和固定调用站点(
last
不是TOTAL
,而是TOTAL-1
)为了正确执行二进制搜索,必须正确排序搜索向量(您案例中的关键字)。在您的示例中,情况并非如此,因为您在“struct”之后有“break”。二进制搜索仅适用于排序的数组,要使代码正常工作,您需要先对关键字进行排序。您试图解决什么问题?在BiSearch实现中放入一些cout
语句?除了二进制搜索需要排序输入这一事实之外,在找到搜索字符串时,除了返回找到的结果之外,不需要其他任何东西,因此我希望else{return mid;}
而肯定不是if(result
。感谢您的建议,当然{return mid;}更好。
#include "BiSearch.h"
SeqWords SW[TOTAL];
int BiSearch(char* des, const char** src, int begin, int last)
{
int result = -1;
while(begin <= last)
{
int mid = (begin + last) / 2;
if(strcmp(src[mid],des) > 0)
last = mid - 1;
else if(strcmp(src[mid],des) < 0)
begin = mid + 1;
else
{
if(result < mid)
result = mid;
begin = mid + 1;
}
}
return result;
}
void initKeyWords(SeqWords* SW)
{
for(int i = 0; i < TOTAL; i++)
{
strcpy(SW[i].keyword,KeyWords[i]);
SW[i].length = strlen(SW[i].keyword);
SW[i].count = 0;
}
}
#include <iostream>
#include <cstring>
#include "BiSearch.h"
#include "GlobalsDefine.h"
using namespace std;
const char* KeyWords[TOTAL] =
{
"auto","double","int","struct","break","else","long","switch",
"case","enum","register","typedef","char","extern","return","union",
"const","float","short","unsigned","continue","for","signed","void",
"default","goto","sizeof","volatile","do","if","while","static",
};
int main()
{
extern SeqWords SW[TOTAL];
initKeyWords(SW);
cout << BiSearch("if", KeyWords, 0, TOTAL) << endl;
cout << BiSearch("for", KeyWords, 0, TOTAL) << endl;
return 0;
}
29
-1