前言
常用的有序序列查询方法:顺序查询、二分查询、索引查询(分块查询)、散列表查询(哈希表查询)、树表查询
注意:这里的哈希表指的是标准的哈希表,外面谈论的哈希集合不少都是散列表(哈希表)和树表结合所致
本章主要介绍顺序查询、二分法查询和索引查询,其他的在后面章节介绍
顺序查询
按照数组从前往后,一个一个进行对比查询,找到即查询到
优点:平常使用较多,使用简单,适用于数量比较少的数组元素
缺点:没有充分利用有序序列的特点优化查询速度
void orderSearch(int value) {
int list[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
for (int i = 0; i < 10; i++) {
if (list[i] == value) {
printf("找到了,索引值是:%d \n", i);
return;
}
}
printf("没找到相关选项 \n");
}
二分法查询
利用有序序列的特种,为了减少查找次数,每次从中间位置开始查找,找到即结束,找不到,则对比数字比中间的大还是小,如果小向前(大向后)取中点继续查找,直到找到或者结束为止
void showBinSearch(int value) {
int list[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int start = 0, end = 9;
int index = -1;
while (start < end) {
int middle = (end + start) / 2;
if (list[middle] == value) {
index = middle;
break;
}
if (list[middle] > value) {
start = middle + 1;
}else {
end = middle - 1;
}
}
if (index == -1) {
printf("没找到相关选项 \n");
}else {
printf("找到了,索引值是:%d \n", index);
}
}
索引(分块)查询
类似于目录,每一个大小章节都有一个页数,形成一个页数序列,而每个章节和都有其章首、章尾索引,其中一个章节就是一个块
每个块结构分为块索引、块起点、块终点
查找方式就跟翻目录一样,知道自己查找那个章节(块索引),然后从章起点(块起点)到章终点(块终点)顺序查找对比即可
//list值列表 blockList块结构列表 blockIndex搜索的块 value搜索的值
int searchIndex(int list[], LSBlockObj blockList[], int blockIndex, int value) {
int res = -1;
for (int i = 0; i < 11; i++) {
LSBlockObj obj = blockList[i];
if (obj.blockIndex != blockIndex) continue;
while (obj.start <= obj.end) {
if (list[obj.start] == value) return list[obj.start];
obj.start++;
}
}
return res;
}