package test;
public class project1 {
public static void main(String []args) {
int []list= {1,3,4,5,6,7,9,12,13,15,18,19};
int key=12;
int result=binarySearch(list,key);
if(result<0) {
System.out.println("not found the number:"+key);
}else {
System.out.println("the index of "+key+" is "+result);
}
}
public static int binarySearch(int []list,int key) {
int low=0;
int hight=list.length-1;
int mid;
while(low<=hight) {
mid=(low+hight)/2;
if(list[mid]<key)
low=mid+1;
else if(list[mid]==key)
return mid;
else hight=mid-1;
}
return -low-1;
}
}
递归二分查找:
package test;
public class project1 {
public static void main(String []args) {
int []list= {1,3,4,5,6,7,9,12,13,15,18,19};
int key=12;
int low=0;
int hight=list.length-1;
int result=binarySearch(list,key,low,hight);
if(result<0) {
System.out.println("not found the number:"+key);
}else {
System.out.println("the index of "+key+" is "+result);
}
}
public static int binarySearch(int []list,int key,int low,int hight) {
int mid=(low+hight)/2;
if(list[mid]<key)
return binarySearch(list,key,mid+1,hight);
else if(list[mid]==key)
return mid;
else return binarySearch(list,key,low,mid-1);
}
}