算法4th: 二分搜索 习题1.1.38

120 阅读1分钟

代码

采用while式:

import edu.princeton.cs.algs4.In;


public class BinarySearch {
    public static int rank(int key, int[] a) {
        int lo = 0;
        int hi = a.length - 1;

        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }

        return -1;
    }

    public static int BruteForceSearch(int key, int[] a) {
        for(int i = 0; i < a.length; i++) {
            if(a[i] == key) return i;
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] a = In.readInts("/Users/truman/Downloads/largeW.txt");
        System.out.println("======二分搜索======");
        long time1 = System.currentTimeMillis();
        int b = BinarySearch.rank(985, a);

        if(b != -1) {
            System.out.println("找到了!索引:" + b);
        } else {
            System.out.println("没找到~");
        }

        long time2 = System.currentTimeMillis();
        System.out.println("时间开销:" + (time2 - time1) + "ms");

        System.out.println("======暴力搜索======");
        long time3 = System.currentTimeMillis();

        int c = BinarySearch.BruteForceSearch(985, a);

        if(b != -1) {
            System.out.println("找到了!索引:" + b);
        } else {
            System.out.println("没找到~");
        }

        long time4 = System.currentTimeMillis();
        System.out.println("时间开销:" + (time4 - time3) + "ms");
    }
}

Output:

======二分搜索======
没找到~
时间开销:0ms
======暴力搜索======
没找到~
时间开销:7ms

思考: 为何不用递归版本???

解答:

使用递归会造成内存溢出! (待补充:《剑指Offer(第二版)》关于递归内存溢出说明)

public static int recursion(int key, int[]a, int lo, int hi) {
    int mid = lo + (hi - lo) / 2;
    if(key < a[mid]) BinarySearch.recursion(key, a, lo, mid - 1);
    else if(key > a[mid]) BinarySearch.recursion(key, a, mid-1, hi);
    else if(key == a[mid]) return mid;

    return -1;
}

Output:

Exception in thread "main" java.lang.StackOverflowError
	at BinarySearch.recursion(BinarySearch.java:21)