基本查找:数组元素无序(从头找到尾)
二分查找(折半查找):前提,数组有序
思想:每次都猜中间的元素,比较大或者小,就能减少一半的元素
代码实现:
package com.gaowei_09;
/*
*
*/
public class ArrayDemo4 {
public static void main(String[] args) {
int[] arr = {11,22,33,44,55,66,77};
int quaryNum = 88;
System.out.println(findNum(arr,quaryNum));
}
private static int findNum(int[] arr,int num) {
int minIndex = 0;
int maxIndex = arr.length-1;
do {
int midIndex = (minIndex + maxIndex)/2;
if(arr[midIndex]==num) {
return midIndex;
}else if(arr[midIndex]>num) {
System.out.println("大了");
maxIndex = midIndex - 1;
}else {
minIndex = midIndex + 1;
System.out.println("小了");
}
}while(minIndex!=maxIndex);
return -1;
}
public static void printArray(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
System.out.print(arr[i] + "]");
} else {
System.out.print(arr[i] + ", ");
}
}
}
}