经典算法之二分查找法

思想:

        二分查找:1.针对的是有序的元素(可以升序,可以降序)

                           2.每次都是在左边界和右边界中间的索引去查询,如果没找到就接着这样去查询,直到某一个边界

                           3.过滤掉边界问题,如果还没找到的话,那么提示要找的值在该数组中不存在

 public static int getValueByHalfSelect() {
        int findValue = 11;
        int findIndex = -1;
        //使用静态初始化的方式定义一个数组。
        int[] arr = {0,1,2,3,4,6};
        //因为最左边的索引和最右边的索引的位置是变化的,所以将其定义成变量
        int leftIndex = 0;
        int ringhtIndex = arr.length - 1;
        //当前的索引
        int currentIndex =  arr.length/2;
        //因为是直到找到才结束,while
        while(true) {
            if(arr[currentIndex] == findValue) {//找到了
                findIndex = currentIndex;
                //输出当前值的索引
                System.out.println("您查询的值:"+findValue + "\r\n它的当前的索引是:"+currentIndex);
                break;
            }else {
                //意思就是:如果等于临界的时候,如果还没有找到此值的话,那么说明此值不存在,也就是需要"退出循环"然后提示"未找到该值"
                if(currentIndex == 0 || currentIndex == arr.length - 1) {
                    break;
                }
                //未找到,然后判断该值与该数组中的数组进行比较
                if(findValue > arr[currentIndex]) {// 4 > 2
                    //向右
                    leftIndex = currentIndex;// 0,1,2,3,4,5 11
                    currentIndex = leftIndex + (ringhtIndex - leftIndex + 1)/2;//不加1的最后一个值取不到。
                }else if(findValue < arr[currentIndex]){
                    //向左
                    ringhtIndex = currentIndex;// 0,1,2,3,4,5
                    currentIndex = leftIndex + (ringhtIndex - leftIndex)/2;
                }
            }
        }
        if(findIndex == -1) {
            System.out.println("该数组中未找到该值");
        }
        return currentIndex;
    }

注意:在向右取值的时候,最右边的索引 - 最左边的索引 + 1;如果不加上1的话,那么最后一个就取不到

猜你喜欢

转载自www.cnblogs.com/donghaibin/p/9057345.html