最近才体会到算法的强大(或者说最近开始接触算法了):
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; }
|
写的不是很清楚,希望可以看的明白
阅读(1882) | 评论(0) | 转发(0) |