TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
使用泛型实现二分查找- 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
源码下载:http://file.javaxxz.com/2014/10/28/235534046.zip |
|