• java的静态查找方法


    参考:https://blog.csdn.net/wqc19920906/article/details/78118968

    二分查找的问题:https://yq.aliyun.com/articles/3670

    静态查找:

    1. 顺序查找;

    /**顺序查找平均时间复杂度 O(n)  
     * @param searchKey 要查找的值  
     * @param array 数组(从这个数组中查找)  
     * @return  查找结果(数组的下标位置)  
     */    
    public static int orderSearch(int target, int[] arr) {    
        if(arr == null || arr.length < 1)  
            return -1;    
        for(int i = 0; i < arr.length; i++) {    
            if (arr[i] == target) {    
                return i;    
            }    
        }    
        return -1;    
    }    

    2. 二分查找;

    private static int binarySearch(int[] arr, int key) {
            int low = 0;
            int high = arr.length - 1;
    
            while (low <= high) {
                int mid = (low + high) >>> 1;
                int midVal = a[mid];
    
                if (midVal < key)
                    low = mid + 1;
                else if (midVal > key)
                    high = mid - 1;
                else
                    return mid; // key found
            }
            return -(low + 1);  // key not found.
        }

    一般的二分查找只要求找到目标元素的位置,但是不保证该位置是否为该元素出现的第一个位置或者最后一个位置,现在想输出该元素第一次出现的位置:

    public class BinarySearchFirstOne {
        public static void main(String[] args) {
            int[] arr = {1,2,3,3,3,4,5,5,6,7,7,7,8,9,9};
            int target = 7;
            System.out.println(search(arr, target));
        }
    //方法代码
    public static int search(int[] arr, int target) { int lo = 0; int hi = arr.length - 1; int mid; while(lo < hi) { mid = (lo + hi) >>> 1; if(arr[mid] < target) { lo = mid + 1; } else hi = mid; } if(arr[lo] == target) { return lo; } else return -1; } }

     3. 分块查找

  • 相关阅读:
    Python-os
    Python-字典Dict
    Linux下使用Apache搭建Web网站服务器
    Linux中FTP安装与配置
    第16章 广域网
    第15章 IPv6
    第14章 思科无线技术
    第13章 网络地址转换NAT
    第12章 安全
    第11章 虚拟局域网
  • 原文地址:https://www.cnblogs.com/xuhaojun/p/9108753.html
Copyright © 2020-2023  润新知