有序数组查找算法:二分法和插值法

/**
 * 有序数组的值查找
 */
public class Search {
    public static void main(String[] args) {
        int[] arr={1,2,3,4,5,6,7,8,9,10};
        //int i = binarySearch3(arr,  3);
        int i = binarySearch(arr, 91);
        System.out.println(i);
    }

    /**
     * 非递归实现二分查找
     * @param arr
     * @param searchVal
     * @return
     */
    static  int binarySearch(int[] arr,int searchVal){
        //初始化左指针
        int left=0;
        //初始化右指针
        int right=arr.length-1;

        //当右指针小于左指针时,说明没有找到,退出循环
        while(right>=left){
            int middle=(left+right)/2;
            int midVal=arr[middle];
            if(midVal>searchVal){
                right=middle-1;
            }else if(midValright){
            return -1;
        }
        int middle=(left + right)/2;
        int midVal=arr[middle];
        if(midVal>searchVal){
            return binarySearch2(arr,left,middle-1,searchVal);
        }else if(midVal stack = new Stack<>();
        stack.push(left);
        stack.push(right);

        while(true){
            int curRight= stack.pop();
            int curLeft= stack.pop();

            if(curLeft>curRight){
                return -1;
            }

            int middle=(curLeft+curRight)/2;
            int midVal=arr[middle];
            if(midVal>searchVal){
               // right=middle-1;
                stack.push(curLeft);
                stack.push(middle-1);

            }else if(midValright || arr[left]>searchVal || arr[right]searchVal){
            return binarySearch2(arr,left,middle-1,searchVal);
        }else if(midVal

 

你可能感兴趣的:(数据结构,二分法,算法,数据结构,stack)