二分法基本查找
public class Kedaxunfei02 {
public static void main(String[] args) {
int [] a = {11,13,15,17,19,21};
System.out.println(binarySearch01(a, 21));
}
public static int binarySearch01(int[] a,int key) {
int start = 0;
int end = a.length-1;
while (start<=end){
int mid = (start+end)/2;
if(key<a[mid])
end = mid-1;
else if(key>a[mid])
start = mid+1;
else
return mid;
}
//没找到返回-1
return -1;
}
}
二分法遍历查找
public class Kedaxunfei02 {
public static void main(String[] args) {
int [] a = {11,13,15,17,19,21};
System.out.println(binarySearch02(a, 21,0,a.length-1));
}
public static int binarySearch02(int[] a,int key,int start,int end) {
while (start<=end){
int mid = (start+end)/2;
if(key<a[mid])
return erfenfa(a, key, start, mid-1);
else if(key>a[mid])
return erfenfa(a, key, mid+1, end);
else
return mid;
}
return -1;
}
}
网友评论