• 14. 二分查找


     给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1

    二分查找

    算法思想:又叫折半查找,要求待查找的序列有序。每次取中间位置的值与待查关键字比较,如果中间位置的值比待查关键字大,则在前半部分循环这个查找的过程,如果中间位置的值比待查关键字小,则在后半部分循环这个查找的过程。直到查找到了为止,否则序列中没有待查的关键字。

    实现:

     1.非递归代码

    复制代码
    public static int biSearch(int []array,int a){
            int lo=0;
            int hi=array.length-1;
            int mid;
            while(lo<=hi){
                mid=(lo+hi)/2;
                if(array[mid]==a){
                    return mid+1;
                }else if(array[mid]<a){
                    lo=mid+1;
                }else{
                    hi=mid-1;
                }
            }
            return -1;
        }
    复制代码

     2.递归实现

    复制代码
    public static int sort(int []array,int a,int lo,int hi){
            if(lo<=hi){
                int mid=(lo+hi)/2;
                if(a==array[mid]){
                    return mid+1;
                }
                else if(a>array[mid]){
                    return sort(array,a,mid+1,hi);
                }else{
                    return sort(array,a,lo,mid-1);
                }
            }
            return -1;
        }
    复制代码

     时间复杂度为 O(logN)   

    查找第一个元素出现的位置(元素允许重复)

    复制代码
    public static int biSearch(int []array,int a){
            int n=array.length;
            int low=0;
            int hi=n-1;
            int mid=0;
            while(low<hi){
                mid=(low+hi)/2;
                if(array[mid]<a){
                    low=mid+1;
                }else{
                    hi=mid;
                }
            }
            if(array[low]!=a){
                return -1;
            }else{
                return low;
            }
        }
    复制代码

    查询元素最后一次出现的位置

    复制代码
    public static int biSearch(int []array,int a){
            int n=array.length;
            int low=0;
            int hi=n-1;
            int mid=0;
            while(low<hi){
                mid=(low+hi+1)/2;
                if(array[mid]<=a){
                    low=mid;
                }else{
                    hi=mid-1;
                }
            }
        
            if(array[low]!=a){
                return -1;
            }else{
                return hi;
            }
        }
    复制代码
  • 相关阅读:
    常用JVM配置参数
    JVM运行机制
    go 奇技淫巧
    如何实现LRU(最近最少使用)缓存淘汰算法?
    数组下标为什么是0而不是1?
    ServiceMesh 演化进程
    CAP定理详解
    vscode 调试配置信息
    Ubuntu 断网问题解决
    ubuntu 关闭指定占用端口
  • 原文地址:https://www.cnblogs.com/Pjson/p/8289333.html
Copyright © 2020-2023  润新知