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 + "}";
}
}
分块查询 java
这段Java代码展示了如何在一个Block类的数组中,通过两个方法getBlockIndex和getindex找到指定数值的块索引。Block类定义了每个块的起始、结束和最大值。
摘要由CSDN通过智能技术生成