分块查询 java

这段Java代码展示了如何在一个Block类的数组中,通过两个方法getBlockIndex和getindex找到指定数值的块索引。Block类定义了每个块的起始、结束和最大值。
摘要由CSDN通过智能技术生成
public class text {
    public static void main(String[] args) throws ParseException {
        int num=6;
        int[] arr={16,5,9,12,21,18,
                32,23,37,26,45,34,
                50,48,61,52,73,66};
        Block b1=new Block(23,0,5);
        Block b2=new Block(45,6,11);
        Block b3=new Block(73,12,17);
        Block[] blockArr={b1,b2,b3};
        System.out.println(getBlockIndex(num, blockArr));
        System.out.println(getindex(blockArr, arr, num));
    }

    private static int getindex(Block[] b,int[] arr,int num) {
        int blockIndex = getBlockIndex(num, b);
        if (blockIndex==-1){
            return -1;
        }
        for (int i = b[blockIndex].getStart(); i <= b[blockIndex].getEnd(); i++) {
            if (arr[i]==num){
                return i;
            }
        }
        return -1;
    }

    private static int getBlockIndex(int num,Block[] b) {
        for (int i = 0; i < b.length; i++) {
            if (num<=b[i].getMax()){
                return i;
            }
        }
        return -1;
    }
}
class Block{
    private int max;
    private int start;
    private int end;

    public Block() {
    }

    public Block(int max, int start, int end) {
        this.max = max;
        this.start = start;
        this.end = end;
    }

    /**
     * 获取
     * @return max
     */
    public int getMax() {
        return max;
    }

    /**
     * 设置
     * @param max
     */
    public void setMax(int max) {
        this.max = max;
    }

    /**
     * 获取
     * @return start
     */
    public int getStart() {
        return start;
    }

    /**
     * 设置
     * @param start
     */
    public void setStart(int start) {
        this.start = start;
    }

    /**
     * 获取
     * @return end
     */
    public int getEnd() {
        return end;
    }

    /**
     * 设置
     * @param end
     */
    public void setEnd(int end) {
        this.end = end;
    }

    public String toString() {
        return "Block{max = " + max + ", start = " + start + ", end = " + end + "}";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值