Chinaunix首页 | 论坛 | 博客
  • 博客访问: 97955
  • 博文数量: 24
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 252
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-12 16:39
文章分类
文章存档

2011年(1)

2009年(17)

2007年(6)

我的朋友
最近访客

分类: C/C++

2007-09-15 11:48:36

最近才体会到算法的强大(或者说最近开始接触算法了):

extern int s;        // 需要查找的那个东东

// 搜索的数列必须是已经排序好的
int lindex = 0;
int rindex = end;    // 左、右索引
int x = (lindex + rindex) / 2;

while (true) {
    if (x == s)
        break;
    else if (x > s)
        rindex = x;
    else
        lindex = x;


    x = (lindex + rindex) / 2;
}


实际应用中(如文件内查找),还再加一项做为上次搜索结果”lastfound",如(这下面是我总结出来的,欢迎指正):

extern FILE *fp;
extern char data;             // 希望匹配的字符

char read = 0;
char lastfound = 0;           // 上次搜索结果

int lindex = 0;
int rindex = FILESIZE - 1;    // 左、右索引
int current = ( lindex + rindex ) / 2;

while (true) {
    fseek(fp,
current, SEEK_SET);
    fread(&read, 1, 1, fp);


    if ((data == read) || (read == lastfound))
        break;
    else if (data > read)
        rindex =
current;
    else
        lindex =
current;


    lastfound = read;
    
current = (lindex+rindex) / 2;
}

写的不是很清楚,希望可以看的明白
阅读(1832) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~