分块查找又称索引顺序查找,它是顺序查找的一种改进方法。
算法流程:
- 先选取各块中的最大关键字构成一个索引表;
- 查找分两个部分:先对索引表进行二分查找或顺序查找,以确定待查记录在哪一块中;然后,在已确定的块中用顺序法进行查找。
class BlockSearch {
private int data[];
private int length;
//查找
public int searchIndex(IndexTable it, int m, BlockSearch nl, int n, int k) {
int low = 0, high = m - 1, mid, i;
int b = n/m;
while(low <= high){
mid = (low + high) / 2;
if(it.elem[mid].key >= k){
high = mid - 1;
}else {
low = mid + 1;
}
}
if(low < m){
i = it.elem[low].start;
while (i <= it.elem[low].start + b - 1 && nl.data[i] != k){
i++;
}
if(i <= it.elem[low].start + b - 1){
return i;
} else {
return -1;
}
}
return -1;
}
//创建数据
public void createSSTable(int[] a){
this.data = new int[a.length];
for(int i = 0; i < a.length; i++){
this.data[i] = a[i];
this.length++;
}
}
//索引表结点
public class IndexItem{
public int key;
public int start;
}
//索引表
public class IndexTable{
public IndexItem[] elem;
public int length = 0;
public void createIndexTable(int[][] b){
this.elem = new IndexItem[b.length];
for(int i = 0; i < b.length; i++){
elem[i] = new IndexItem(); //防止报空
elem[i].key = b[i][0];
elem[i].start = b[i][1];
this.length++;
}
}
}
public static void main(String[] args)
{
int[] a = {8, 14, 6, 9, 10, 22, 34, 18, 19, 31, 40, 38, 54, 66, 46};
int[][] b = {{14, 0},{34, 5},{66, 10}};
BlockSearch nl = new BlockSearch();
IndexTable it = nl.new IndexTable();
nl.createSSTable(a);
it.createIndexTable(b);
int x = nl.searchIndex(it, b.length, nl, a.length, 10);
if(x < 0){
System.out.println("要查找的元素不存在");
}else {
System.out.println("查找成功,该元素在表中的位置为:" + (x + 1));
}
}
}