二分查找

2011-03-03  李卓华 


public class BinarySearch {

public static void main(String [] args){
int [] a = {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10};
System.out.println(binarySearch(a, 11));
}
public static int binarySearch(int [] a, int n){
int low = 0;
int high = a.length - 1;
while(low <= high){
int mid = a[(low+high)/2];
if(mid == n){
return mid;
}
else if(n > mid){
low = (low+high) / 2 + 1;
}
else{
high = (low+high) / 2 - 1;
}
}
return -1;
}
}
244°/2449 人阅读/0 条评论 发表评论

登录 后发表评论