查找算法

二分查找

二分查找的输入必须是一个有序的元素列表

二分查找的时间复杂度:log2n

package suanfa.erfen;

/**
 * @ClassName: Test
 * @Description:
 */
public class Test {
    public static void main(String[] args) {
        int[] array={1,2,3,4,6,7,8,10,23,24,45};
        int re=getValue2(array,1);
        System.out.println(re);
    }
    
    /**
     * @Description: 递归的方式实现二分查找
     * @parameter: array
     * @parameter: start
     * @parameter: end
     * @parameter: val
     * @return: int
     */
    public static int getValue(int[] array,int start,int end,int val){
        if(start>end){
            return -1;
        }

        if(start==end){
           if(val==array[start]){
               return start;
           }else {
               return -1;
           }
        }
        int mid=(start+end)/2;
        if(val==array[mid]){
            return mid;
        }else if(val<array[mid]){
            return getValue(array,start,mid-1,val);
        }else {
            return getValue(array,mid+1,end,val);
        }
    }

    /**
     * @Description: 采用循环的方式替代递归实现二分查找
     * @parameter: array
     * @parameter: val
     * @return: int
     */
    public static int getValue2(int[] array,int val){
        int start=0;
        int end=array.length-1;
        while (start<end){
            int mid=(start+end)/2;
            if(val==array[mid]){
                return mid;
            }else if(val<array[mid]){
                end=mid-1;
            }else {
                start=mid+1;
            }
        }
        if(start==end){
            if(val==array[start]){
                return start;
            }else {
                return -1;
            }
        }
        return -1;
    }
}
View Code

在循环中进行二分查找

    public static int binarySearch_loop(int[] array,int value){
        int start = 0;
        int end = array.length;
        int index=-1;
        while (start != end){
            int mid=(start+end)/2;
            if(value==array[mid]){
                index=mid;
                break;
            }else if(value<array[mid]){
                end=mid;
            }else {
                start=mid;
            }
        }
        return index;
    }
View Code

递归的进行二分查找

    public static int  binarySearch_recursion(int[] array,int start,int end,int value){
        int mid = ( start + end ) / 2;
        if(value == array[mid]){
            return mid;
        }else if(value < array[mid]){
            if(start == mid){
                return -1;
            }
            return binarySearch_recursion(array,start,mid,value);
        }else {
            if(end == mid){
                return -1;
            }
            return binarySearch_recursion(array,mid,end,value);
        }
    }
View Code

 

posted @ 2020-07-08 07:56  弱水三千12138  阅读(136)  评论(0编辑  收藏  举报