分块查找多适用于块间有序,块内无序。
对下列数字进行查找。
16, 5, 9, 12, 21, 18, 32, 23, 37, 26, 45, 34, 50, 48, 61, 52, 73, 66
1.将数字存储在数组中
2.进行分块,保证第一块的最大值比第二块的最小值小,以此类推。尽量保证块数为:数字总数开根号
3.获取块间的索引值
4.然后获取块内索引值得到最终索引值。
代码实现:
package com.itheima.find;
public class blocksearch {
public static void main(String[] args) {
int[] arr = {16, 5, 9, 12, 21, 18,
32, 23, 37, 26, 45, 34,
50, 48, 61, 52, 73, 66};
Block b1 = new Block(21, 0, 5);
Block b2 = new Block(45, 6, 11);
Block b3 = new Block(73, 12, 17);
Block[] blockArr = {b1, b2, b3};
int number = 66;
int index = getIndex(blockArr, arr, number);
System.out.println(index);
}
// 获取块内索引
private static int getIndex(Block[] blockArr, int[] arr, int num) {
int indexBlock = findIndexBlock(blockArr, num);
if (indexBlock == -1) {
return -1;
}
int startIndex = blockArr[indexBlock].getStartIndex();
int endIndex = blockArr[indexBlock].getEndIndex();
for (int i = startIndex; i <= endIndex; i++) {
if (arr[i] == num) {
return i;
}
}
return -1;
}
// 获取块间索引
public static int findIndexBlock(Block[] blockArr, int num) {
for (int i = 0; i < blockArr.length; i++) {
if (num <= blockArr[i].getMax()) {
return i;
}
}
return -1;
}
}
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;
}
public String toString() {
return "Block{max = " + max + ", startIndex = " + startIndex + ", endIndex = " + endIndex + "}";
}
}
运行演示:(得到的是该数字的索引值)