1.必须是顺序存储结构
2.数据已经有序
public class BinaryTest {
public static void main(String[] args) {
HashMap set=new HashMap();
int [] arr = {3,6,9,11,33,45,67};
int index =45;
int search = binarySearch(arr,index);
System.out.println(search);
System.out.println(tt(arr,index,0,arr.length-1));
}
//非递归
private static int binarySearch(int[] arr, int index) {
int low = 0;
int height = arr.length-1;
while(low<=height) {
int mid = (low+height)/2;
if(index==arr[mid]) {
return mid;
}else if(index>arr[mid]) {
low=mid+1;
}else if(index<arr[mid]) {
height = mid -1;
}
}
return -1;
}
//递归
private static int tt(int[] arr, int index,int low ,int height) {
if(arr == null) {
System.out.println("是空数组");
return -1;
}
if(arr.length ==1) {
return arr[0]==index?0:-1;
}
if(low>height) {
return -1;
}
int mid = (low+height)/2;
if(arr[mid]==index) {
return mid;
}else if(index>arr[mid]) {
return tt(arr,index,mid+1,height);
}else if(index<arr[mid]){
return tt(arr,index,low,mid-1);
}
return -1;
}
}
结果
5
5