对于无序且无规律的数据,分块思想可以转变成,要使用每一块的数据范围不能有交集的思想
public class BlockSearchDemo2 { public static void main(String[] args) { /* 分块查找[无规律的数据] 核心思想: 块内无序,块间无序 实现步骤: 1.创建数组blockArr存放每一个块对象的信息 2.先查找blockArr确定要查找的数据属于哪一块 3.再单独遍历这一块数据即可 */ int[] arr = {27, 22, 30, 40, 36, 13, 19, 16, 20, 7, 10, 43, 50, 48}; Block1 b1 = new Block1(22, 40, 0, 3); Block1 b2 = new Block1(13, 36, 4, 8); Block1 b3 = new Block1(7, 10, 9, 10); Block1 b4 = new Block1(43, 50, 11, 13); //定义数组用来管理四个块的对象(索引表) Block1[] blockArr1 = {b1, b2, b3, b4}; //定义一个变量用来记录要查找的元素 int number = 48; //调用方法,传递索引表,数组,要查找的元素 int index = getIndex(arr, blockArr1, number); //打印一下 System.out.println(index); } private static int getIndex(int[] arr, Block1[] blockArr1, int number) { //1.确定number是在那一块当中 int indexBlock = findIndexBlock(blockArr1, number); if (indexBlock == -1) { //表示number不在数组当中 return -1; } //2.获取这一块的起始索引和结束索引 --- 30 // Block b1 = new Block(21,0,5); ---- 0 // Block b2 = new Block(45,6,11); ---- 1 // Block b3 = new Block(73,12,17); ---- 2 int startIndex = blockArr1[indexBlock].getStartIndex(); int endIndex = blockArr1[indexBlock].getEndIndex(); //3.遍历 for (int i = startIndex; i <= endIndex; i++) { if (arr[i] == number) { return i; } } return -1; } //定义一个方法,用来确定number在哪一块当中 public static int findIndexBlock(Block1[] blockArr1, int number) { //100 //从0索引开始遍历blockArr,如果number小于max,那么就表示number是在这一块当中的 for (int i = 0; i < blockArr1.length; i++) { if (number <= blockArr1[i].getMax()) { return i; } } return -1; } } class Block1 { private int min; //最小值 private int max;//最大值 private int startIndex;//起始索引 private int endIndex;//结束索引 public Block1() { } public Block1(int min, int max, int startIndex, int endIndex) { this.min = min; this.max = max; this.startIndex = startIndex; this.endIndex = endIndex; } /** * 获取 * * @return min */ public int getMin() { return min; } /** * 设置 * * @param min */ public void setMin(int min) { this.min = min; } /** * 获取 * * @return max */ public int getMax() { return max; } /** * 设置 * * @param max */ public void setMax(int max) { this.max = max; } /** * 获取 * * @return startIndex */ public int getStartIndex() { return startIndex; } /** * 设置 * * @param startIndex */ public void setStartIndex(int startIndex) { this.startIndex = startIndex; } /** * 获取 * * @return endIndex */ public int getEndIndex() { return endIndex; } /** * 设置 * * @param endIndex */ public void setEndIndex(int endIndex) { this.endIndex = endIndex; } public String toString() { return "Block1{min = " + min + ", max = " + max + ", startIndex = " + startIndex + ", endIndex = " + endIndex + "}"; } }
运行结果