二分法抽象数据类型实战

一 数据抽象作用

  • 准确定义算法能为用例提供什么。

  • 隔离算法的实现和用例代码。

  • 实现多层次抽象,用已知算法实现其他算法。

二 二分法查找API

public class StaticSETofInts

public StaticSETofInts(int[] keys)

根据keys[]中的所有值创建一个集合。

public boolean contains(int key)

key是否存在于集合中。

三 典型用例

package BinarySearch;

import common.In;
import common.StdIn;
import common.StdOut;

public class Whitelist {

    // Do not instantiate.
    private Whitelist() { }

    public static void main(String[] args) {
        In in = new In(args[0]);
        int[] white = in.readAllInts();
        StaticSETofInts set = new StaticSETofInts(white);

        // Read key, print if not in whitelist.
        while (!StdIn.isEmpty()) {
            int key = StdIn.readInt();
            if (!set.contains(key))
                StdOut.println(key);
        }
    }
}

四 数据类型的实现

package BinarySearch;

import java.util.Arrays;

public class StaticSETofInts {
    private int[] a;
    public StaticSETofInts(int[] keys) {

        // defensive copy
        a = new int[keys.length];
        for (int i = 0; i < keys.length; i++)
            a[i] = keys[i];

        // sort the integers
        Arrays.sort(a);

        // check for duplicates
        for (int i = 1; i < a.length; i++)
            if (a[i] == a[i-1])
                throw new IllegalArgumentException("Argument arrays contains duplicate keys.");
    }

    public boolean contains(int key) {
        return rank(key) != -1;
    }


    public int rank(int key) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            // Key is in a[lo..hi] or not present.
            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;
    }
}

五 测试

1 largeW.txt文件内容

944443
293674
572153
600579
499569
984875
763178
295754

2 largeT.txt文件内容

944443
293674
572153
600579
499569
984875
763178
295754
1
2
3
4
5

3 测试结果

F:\Algorithm\target\classes>java BinarySearch.Whitelist largeW.txt < largeT.txt
1
2
3
4
5
发布了4080 篇原创文章 · 获赞 538 · 访问量 296万+

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/103943650