|
使用泛型实现二分查找
public class Test{
public static < T extends Comparable < ? super T>> int binarySearch(T [] array,T key){
int low = 0;
int high = array.length-1;
while(low <= high){
int mid = (low + high)/2;
if(array[mid].compareTo(key)< 0){
low = mid + 1;
}else if(array[mid].compareTo(key)>0){
high = mid - 1;
}else{
return mid;
}
}
return -1;
}
public static void main(String args[]){
Integer a[]={1,2,3,4,5,6,7,8,9};
int k=binarySearch(a,7);
System.out.println("k="+k);
}
}
出处http://wujuxiang.blog.51cto.com/2250829/410763 |
|