分块查找1

本文介绍了Java代码实现的一个分块查找算法,通过定义block类和相关方法,对给定的目标数组进行划分,以提高查找效率。
摘要由CSDN通过智能技术生成
public class deom {
    public static void main(String[] args) {
        int[] arr = {16,5,9,12,21,18,
                32,23,37,26,45,34,
                50,48,61,52,66,73};//目标数组
        block b1 = new block(21,0,5);
        block b2 = new block(45,6,11);
        block b3 = new block(73,12,17);
        block[] barr = {b1,b2,b3};
        int number = 16;
        int n = getIndex(number,barr,arr);
        System.out.println(n);
    }
    public static int getIndex(int number,block[] barr,int[] arr){//分块查找
        block b = getNumber(number,barr);
        if(b==null){
            return -1;
        }
        else{
            for(int i=b.getStartIndex();i<=b.getEndIndex();i++){
                if(number==arr[i]){
                    return i;
                }
            }
            return -1;
        }
    }
    public static block getNumber(int number,block[] barr){//获取查找区间
        for(int i=0;i<barr.length;i++){
            if(number>barr[i].getMax()){
                continue;
            }
            if(number<barr[i].getMax()){
                return barr[i];
            }
        }
        return null;
    }
}

class block{
    private int max;
    private int startIndex;
    private int endIndex;

    public block() {
    }

    public block(int max, int startIndex, int endIndex) {
        this.max = max;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
    }

    public int getMax() {
        return max;
    }

    public void setMax(int max) {
        this.max = max;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }

    public int getEndIndex() {
        return endIndex;
    }

    public void setEndIndex(int endIndex) {
        this.endIndex = endIndex;
    }
}//划分类
  • 7
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值