分块查找的实现(Java)与讲解-常见数据结构
1、算法概述
分块查找法(Blocking Search)又称为索引顺序查找法,在此查找法中,除了原表本身以外还需要建立一个“索引表”,即将原表分成一块一块,每一块选取其最大的记录作为关键字项,块中的起始下标为块的指针项。索引表按照关键字有序,即块与块之间有序,块内元素无序。查找时先确定待查找的记录在哪一块,再在具体某个块内使用顺序查找法查找其具体位置。故其性能介于顺序查找法和折半查找法之间。
时间复杂度:不超过O(n)
空间复杂度:不超过O(n)
优点:
- 在表中插入和删除元素时,只需要找到对应的块,就可以在块内进行插入和删除运算
- 块内无序,插入和删除都较为容易,无需进行大量移动
- 适合线性表既要快速查找又要经常动态变化的场景
缺点:
- 需要增加一个存储索引表的内存空间
- 需要对初始索引表按照其最大关键字(或最小关键字)进行排序运算
2、代码实现
package top.alibra.algorithm;
public class ChunkedLookup {
private static int ChunkedLookupSearch(int a[],BlockTable[] arr,int key){
int left=0,right=arr.length-1;
//利用折半查找法查找元素所在的块,就是索引块 right初使为3
while(left<=right){
int mid=(right-left)/2+left;//采用折半查找
if(arr[mid].key>=key){
right=mid-1;
}else{
left=mid+1;
}
}
if(left> arr.length-1||right<0){
//表示在两边,没有合适的
return -1;
}
//循环结束,元素所在的块为right+1 取对应左区间下标作为循环的开始点
//因为arr[mid].key>=key,所以真实所在块总是比right大一个,所以要+1
int i=arr[right+1].low;
//在块内进行顺序查找确定记录的最终位置
while(i<=arr[right+1].high&&a[i]!=key){
i++;
}
//如果下标在块的范围之内,说明查找成功,否则失败
if(i<=arr[right+1].high){
return i;
}else{
return -1;
}
}
//测试
public static void main(String[] args) {
//原表
int a[]={8,21,11,13,34,41,43,39,49,60,58,47,79,80,77,82};
//分块获得对应的索引表,这里是一个以索引结点为元素的对象数组
BlockTable [] arr={
new BlockTable(21,0,3),//最大关键字为22 起始下标为0,3的块
new BlockTable(43,4,7),
new BlockTable(60,8,11),
new BlockTable(82,12,15)
};
//待查关键字
// int key=1;
// int key=9;
// int key=431;
int key=43;
//调用分块查找算法,并输出查找的结果
int result=ChunkedLookupSearch(a,arr,key);
System.out.print("数组下标:"+result);
}
}
//索引表结点
class BlockTable{
int key;
int low;
int high;
BlockTable(int key,int low,int high){
this.key=key;
this.low=low;
this.high=high;
}
}