java泛型的二分查找

原创
2016/07/22 00:19
阅读数 110

随便测试了一下不知道是否完全正确


/**
 * Created by Void Young on 7:57 PM 6/25/2016 .
 * IDEA-Test .
 * 泛型二分查找
 *此处返回的负数为在list里1开始计算的次序位置,不是数组下标
 */
public class GenericBinarySearch {

    public static <E extends Comparable<E>> int binarySearch (E[] list,E key){
        int low = 0,high = list.length-1,middle = 0,flag = 0;
        while (low<=high) {
            middle = (low+high)/2;
            flag = key.compareTo (list[middle]);
            if (flag > 0) {
                low = middle+1;
            } else if (flag < 0) {
                high = middle - 1;
            } else {
                return middle;//找到了就返回下标
            }
        }
        
        return - ( low + 1 );
    }

    public static void main (String[] args) {
         Integer[] list = {- 2, 0, 1, 5, 7, 8, 9, 15, 25, 35, 65, 88, 90};
        Double[] dlist = {- 18.5, - 5.1, 0.0, 1.1, 25.3, 35.8, 44.5};
        System.out.println ( binarySearch (dlist, 25.1));
    }
}


展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部