分块查找算法

分块查找又称索引顺序查找,它是顺序查找的一种改进方法。

算法流程:

  • 先选取各块中的最大关键字构成一个索引表
  • 查找分两个部分:先对索引表进行二分查找顺序查找,以确定待查记录哪一块中;然后,在已确定的块中用顺序法进行查找。

在这里插入图片描述

图片借自https://blog.csdn.net/qq_27870421/article/details/106773548?utm_medium=distribute.pc_relevant.none-task-blog-title-1&spm=1001.2101.3001.4242

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));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/gjs935219/article/details/108625221