Java实现查找算法系列

最近在刷面试题,刷剑指Offer,经常遇到查找的问题,今天就查找资料总结一下几种常见的查找方法,并且使用Java代码实现。
1、顺序查找

        基本思想:顺序查找也称为线形查找,属于无序查找算法。从数据结构线形表的一端开始,顺序扫描,依次将扫描到的结点关键字与给定值keyword相比较,若相等则表示查找成功;若扫描结束仍没有找到关键字等于keyword的结点,表示查找失败。

       时间复杂度:查找成功时的平均查找长度为:(假设每个数据元素的概率相等) ASL = (1+2+3+…+n)/n = (n+1)/2 ;

当查找不成功时,需要n+1次比较,时间复杂度为O(n);

        顺序查找适合于存储结构为顺序存储或链接存储的线性表。

Java代码实现:

/**
 * 顺序查找
 * @author zhang
 * @create 2018-05-19-9:24
 */
public class OrderSearch {
    public static void main(String[] args) {

        int[] arr = {2, 3, 2, 1, 5, 7, 8, 4};
        int N = arr.length;
        int keyword = 7;
        System.out.println( orderSearch(arr, N, keyword));
    }

    private static int orderSearch(int[] arr,int N, int keyword) {

        for (int i = 0; i < N; i++) {
            if (arr[i] == keyword) {
                return i;
            }
        }
        return -1;
    }
}
5
2、二分查找

        基本思想:也称为是折半查找,属于有序查找算法。用给定值k先与中间结点的关键字比较,中间结点把线形表分成两个子表,若相等则查找成功;若不相等,再根据k与该中间结点关键字的比较结果确定下一步查找哪个子表,这样递归进行,直到查找到或查找结束发现表中没有这样的结点。

        时间复杂度:最坏情况下,关键词比较次数为log2(n+1),且期望时间复杂度为O(log2n);

        折半查找的前提条件是需要有序表顺序存储,对于静态查找表,一次排序后不再变化,折半查找能得到不错的效率。但对于需要频繁执行插入或删除操作的数据集来说,维护有序的排序会带来不小的工作量,那就不建议使用。

Java代码实现:

/**
 * 二分查找
 *
 * @author zhang
 * @create 2018-05-19-9:33
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 2, 4, 6, 8, 9, 13, 15};
        int low = 0;
        int high = arr.length - 1;
        int keyword = 4;

        System.out.println(binarySearch(arr, low, high, keyword));
        System.out.println(binarySearch2(arr, low, high, keyword));
    }
    //递归算法
    public static int binarySearch(int[] arr, int low, int high, int keyword) {

        int mid = (low + high) / 2;
        if (low > high) {
            return -1;
        }
        if (arr[mid] == keyword) {
            return mid;
        }
        if (arr[mid] > keyword) {
            return binarySearch(arr, low, mid-1,keyword);
        }
        if (arr[mid] < keyword) {
            return binarySearch(arr, mid+1, high,keyword);
        }
        return -1;
    }
    //无递归算法实现
    public static int binarySearch2(int[] arr, int low, int high, int keyword){
        while (low <= high) {
            int mid = (low + high) / 2;
            if (arr[mid] == keyword) {
                return mid;
            } else if (arr[mid] > keyword) {
                high = mid - 1;
            }else {
                low = mid + 1;
            }
        }
        return -1;
    }
}
2
2
3、插值查找

        基本思想:基于二分查找算法,将查找点的选择改进为自适应选择,可以提高查找效率,根据要查找的关键字 keyword 与查找表中最大最小记录的关键字比较后的查找方法,其核心就在于插值的计算公式mid=(keyword - arr[low])/(arr[high] - arr[low])。mid = low + ((key - a[low])/(a[high] - a[low]))(high - low)

       例如arr[11]={0,1,16,24,35,47,59,62,73,88,99},low=1,high=10,则arr[low]=1,arr[high]=99,如果我们要找的是keyword=16时,按原来的折半查找的做法,我们需要四次才可以得到结果,但如果使用新办法,(keyword - arr[low])/(arr[high] - arr[low])=(16-1)/(99-1)≈0.153,即mid≈1+0.153*(10-1)=2.377取整得到mid=2,我们只需要两次查找到结果了,显著大大提高了查找的效率。

        时间复杂度:为O(logn),对于表长较大,而关键字分布又比较均匀的查找表来说,插值查找算法的平均性能比折半查找要好得多。若数组中如果分布类似{0,1,2,2000,2001,……,999998,999999}极端不均匀的数据时,不建议采用插值查找。

代码实现:

/**
 * 插值查找
 *
 * @author zhang
 * @create 2018-05-20-15:32
 */
public class InsertionSearch {
    public static void main(String[] args) {
        int[] arr = {1, 2, 4, 6, 8, 9, 13, 15};
        int low = 0;
        int high = arr.length - 1;
        int keyword = 2;

        System.out.println(insertionSearch(arr, low, high, keyword));
        System.out.println(insertionSearch(arr, low, high, keyword));
    }

    private static int insertionSearch(int[] arr, int low, int high, int keyword) {
        while (low <= high) {
            int mid = low + ((keyword - arr[low]) / (arr[high] - arr[low]))*(high-low);
            if (arr[mid] == keyword) {
                return mid;
            } else if (arr[mid] > keyword) {
                high = mid - 1;
            }else {
                low = mid + 1;
            }
        }
        return -1;
    }
}
4、斐波那契查找

        基本思想:斐波那契查找就是在二分查找的基础上根据斐波那契数列进行分割的。在斐波那契数列找一个等于大于查找表中元素个数的数F[n],将原查找表扩展为长度为F[n](如果要补充元素,则补充重复最后一个元素,直到满足F[n]个元素),完成后进行斐波那契分割,即F[n]个元素分割为前半部分F[n-1]个元素,后半部分F[n-2]个元素,找出要查找的元素在那一部分并递归,直到找到。

        时间复杂度:时间复杂度还是O(log 2n ),但是与二分查找相比,斐波那契查找的优点是它只涉及加法和减法运算,而不用除法,而除法比加减法要占用更多的时间,因此,斐波那契查找的运行时间理论上比折半查找小。

        斐波那契数列,又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21、····,在数学上,斐波那契被递归方法如下定义:F(1)=1,F(2)=1,F(n)=f(n-1)+F(n-2) (n>=2)。该数列越往后相邻的两个数的比值越趋向于黄金比例值(0.618)。

Java代码实现:
/**
 * 斐波那契查找
 *
 * @author zhang
 * @create 2018-05-20-15:46
 */
public class FibonacciSerach {

    private final static int MAXSIZE = 20;

    public static void main(String[] args) {
        int[] f = fibonacci();
        for(int i:f){
            System.out.print(i+" ");
        }
        System.out.println();

        int[] arr = {3, 5, 6, 16, 24, 35, 36, 37, 43, 44, 48, 52, 66};

        int keyword = 36;
        int position = fibonacciSearch(arr,keyword);
        System.out.println("值"+keyword+"的元素位置为:"+position);
    }

    private static int[] fibonacci(){
        int[] f = new int[20];
        int i =0;
        f[0] = 1;
        f[1] = 1;
        for(i=2;i<MAXSIZE;i++){
            f[i] = f[i-1]+f[i-2];
        }
        return f;
    }
    private static int fibonacciSearch(int[] arr,int keyword){
        int low = 0;
        int high = arr.length-1;
        int mid = 0;
        //斐波那契分割数值下标
        int k = 0;
        //序列元素个数
        int i=0;
        // 获取斐波那契数列
        int[] f = fibonacci();
        //获取斐波那契分割数值下标
        while(arr.length>f[k]-1){
            k++;
        }
        //创建临时数组
        int[] temp = new int[f[k]-1];
        for(int j=0;j<arr.length;j++){
            temp[j] = arr[j];
        }
        //序列补充至f[k]个元素,补充的元素值为最后一个元素的值
        for(i=arr.length;i<f[k]-1;i++){
            temp[i]=temp[high];
        }
        //遍历打印出临时数组中的元素
        for(int j:temp){
            System.out.print(j+" ");
        }
        System.out.println();

        while( low <= high )
        {
            // low:起始位置
            // 前半部分有f[k-1]个元素,由于下标从0开始
            // 则-1 获取 黄金分割位置元素的下标
            mid = low + f[k-1] - 1;

            if( temp[mid] > keyword )
            {
                // 查找前半部分,高位指针移动
                high = mid - 1;
                // (全部元素) = (前半部分)+(后半部分)
                //   f[k]  =  f[k-1] + f[k-1]
                // 因为前半部分有f[k-1]个元素,所以 k = k-1
                k = k - 1;
            }else if( temp[mid] < keyword )
            {
                // 查找后半部分,高位指针移动
                low = mid + 1;
                // (全部元素) = (前半部分)+(后半部分)
                //   f[k]  =  f[k-1] + f[k-1]
                // 因为后半部分有f[k-1]个元素,所以 k = k-2
                k = k - 2;
            }else{
                //如果为真则找到相应的位置
                if( mid <= high )
                {
                    return mid;
                }else{
                    //出现这种情况是查找到补充的元素
                    //而补充的元素与high位置的元素一样
                    return high;
                }
            }
        }
        return -1;
    }
}
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 
3 5 6 16 24 35 36 37 43 44 48 52 66 66 66 66 66 66 66 66 
值36的元素位置为:6
5、分块查找

       基本思想:将n个数据元素"按块有序"划分为m块(m ≤ n)。每一块中的结点不必有序,但块与块之间必须"按块有序";即第1块中任一元素的关键字都必须小于第2块中任一元素的关键字;而第2块中任一元素又都必须小于第3块中的任一元素,……然后使用二分查找及顺序查找。

        查找步骤:

        1 先选取各块中的最大关键字构成一个索引表;

   2 查找分两个部分:先对索引表进行二分查找或顺序查找,以确定待查记录在哪一块中;然后,在已确定的块中用顺序法进行查找。

        时间复杂度:O(log(m)+N/m)。

        分块查找又称索引顺序查找,它是顺序查找的一种改进方法。

Java代码实现:

 
 
/**
 * 分块查找
 *
 * @author zhang
 * @create 2018-05-19-10:07
 */
//分块查找的实现
public class BlockSearch {

    private int[] index;
    private ArrayList[] list;

    public static void main(String[] args) {
        int[] index = {10, 20, 30};
        BlockSearch blocksearch = new BlockSearch(index);
        blocksearch.insert(1);
        blocksearch.insert(12);
        blocksearch.insert(22);

        blocksearch.insert(9);
        blocksearch.insert(18);
        blocksearch.insert(23);

        blocksearch.insert(5);
        blocksearch.insert(15);
        blocksearch.insert(27);

        blocksearch.printAll();

        System.out.println(blocksearch.search(18));
        System.out.println(blocksearch.search(29));
    }

    //初始化索引表
    public BlockSearch(int[] index) {
        if (index != null && index.length != 0) {

            this.index = index;
            this.list = new ArrayList[index.length];

            //初始化容器
            for (int i = 0; i < list.length; i++) {
                list[i] = new ArrayList();
            }
        } else {
            throw new Error("index cannot be null or empty");
        }
    }
    //插入元素
    public void insert(int keyword) {
        int i = binarysearch(keyword);
        list[i].add(keyword);
    }

    //二分查找,找出需要插入元素需要插入块的位置
    private int binarysearch(int keyword) {
        int low = 0;
        int high = index.length - 1;
        int mid = -1;
        while (low <= high) {
            mid = (low + high) / 2;
            if (index[mid] > keyword) {
                high = mid - 1;
            } else{
                low = mid + 1;
            }
        }
        return low;
    }

    //查找元素
    public boolean search(int data) {
        int i = binarysearch(data);
        for (int j = 0; j < list[i].size(); j++) {
            if (data == (int) list[i].get(j)) {
                System.out.println(String.format("查找元素为第: "+i+1+"块  第"+j + 1+"个 元素"));
                return true;
            }
        }
        return false;
    }

    //打印每块元素
    public void printAll() {
        for (int i = 0; i < list.length; i++) {

            System.out.println("ArrayList" + i + ":");

            for (int j = 0; j < list[i].size(); j++) {
                System.out.println(list[i].get(j) + "  ");
            }
        }
    }


ArrayList0:
1  
9  
5  
ArrayList1:
12  
18  
15  
ArrayList2:
22  
23  
27  
查找元素为第: 11块  第11个 元素
true
false






















猜你喜欢

转载自blog.csdn.net/weixin_39788856/article/details/80371552