public class Test {
public static class Block {
/*block的索引,用来标识块中元素*/
public int index;
/*该block的开始位置*/
public int start;
/*块元素长度,在该例子中0代表空元素,不计入block长度*/
public int length;
public Block(int index, int start, int length) {
this.index = index;
this.start = start;
this.length = length;
}
}
/*主表*/
static int[] valueList = new int[]{
104, 101, 103, 105,102, 0, 0, 0, 0, 0,
201, 202, 204, 203,0, 0, 0, 0, 0, 0,
303, 301, 302, 0, 0, 0, 0, 0, 0, 0
};
/*索引表*/
static Block[] indexList = new Block[]{
new Block(1, 0, 5),
new Block(2, 10, 4),
new Block(3, 20, 3)
};
public static void main(String[] args) {
System.out.println("原始主表:");
printElemts(valueList);
/*分块查找*/
int searchValue = 203;
System.out.println("元素"+searchValue+",在列表中的索引为:"+blockSearch(searchValue)+"\n");
/*插入数据并查找*/
int insertValue = 106;
/*插入成功,查找插入位置*/
if (insertBlock(insertValue)) {
System.out.println("插入元素"+insertValue+"后的主表:");
printElemts(valueList);
System.out.println("元素" + insertValue + "在列表中的索引为:" + blockSearch(insertValue));
}
}
public static void printElemts(int[] array) {
for(int i = 0; i < array.length; i++){
System.out.print(array[i]+" ");
if ((i+1)%10 == 0) {
System.out.println();
}
}
}
/*插入数据*/
public static boolean insertBlock(int key) {
Block item = null;
/*确定插入到哪个块中,在该例子中,第一个block中放的是100-200之间的数,第二个block中放的是200-300之间的数,以此类推*/
int index = key/100;
int i = 0;
/*找到对应的block*/
for (i = 0; i < indexList.length; i++) {
if (indexList[i].index == index) {
item = indexList[i];
break;
}
}
/*如果数组中不存在对应的块,则不能插入该数据*/
if (item == null) {
return false;
}
/*将元素插入到每个块的最后*/
valueList[item.start + item.length] = key;
/*更新该块的长度*/
indexList[i].length++;
return true;
}
public static int blockSearch(int key) {
Block indexItem = null;
/*确定插入到哪个块中,在该例子中,第一个block中放的是100-200之间的数,第二个block中放的是200-300之间的数,以此类推*/
int index = key/100;
/*找到对应的block*/
for(int i = 0;i < indexList.length; i++) {
if(indexList[i].index == index) {
indexItem = indexList[i];
break;
}
}
/*如果数组中不存在对应的块,则返回-1,查找失败*/
if(indexItem == null)
return -1;
/*在对应的block中查找*/
for(int i = indexItem.start; i < indexItem.start + indexItem.length; i++) {
if(valueList[i] == key)
return i;
}
return -1;
}
}