C ++二进制搜索关键字错误

时间:2015-08-03 08:40:54

标签: 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 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

BiSearch.cpp

#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;
    }
}

Main.cpp的

#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

3 个答案:

答案 0 :(得分:2)

二进制搜索需要对数组进行排序,这不是你的情况。

带有已排序输入的

Live Demo,以及具有固定调用网站的last不是TOTAL,而是TOTAL - 1

答案 1 :(得分:1)

为了正确执行二进制搜索,必须正确排序搜索向量(在您的情况下为KeyWords)。在你的例子中并非如此,因为你在'struct'之后'break',例如。

答案 2 :(得分:1)

二进制搜索仅适用于排序数组,为了使您的代码正常工作,您需要先对KeyWords进行排序。