凡是用二分查找的方法时,数组必须是有序的(即二分要先排序)
折半查找
import java.util.Scanner;
public class ArrayWork{
public static void main(String[] args){
int[] arr = {1,2,3,4,5,6,7,8,9,10,11,12,33,55,88};
System.out.println("请输入要查找的数:");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int index = -1;//保存找到数所在数组中的下标,找不到等于-1
int start = 0;///起始下标
int end = arr.length-1;//终止下标
int middle;
int count = 0;
while(start<=end){
count++;
middle = (start+end)/2;
if(num == arr[middle]){
index = middle+1;
break;
}
if(num>arr[middle]){
start = middle+1;
}
if(num<arr[middle]){
end = middle-1;
}
}
if(index == -1){
System.out.println("Not find");
}else{
System.out.println("Find this number at\t"+index);
}
}
}