查找算法实现

1. 折半查找

使用折半查找的前提是元素已经排序。
代码实现:先定义接口Search

package org.util.search;

/** * 查找 * @author Weibing Long * @since 2018.04.13 */
public interface Search {
    boolean search(int[] x, int key);
}

然后实现方法

package org.util.search;

/** * 折半查找,使用折半查找的前提是元素已经排序 * @author Weibing Long * @since 2018.04.13 */
public class BinarySearch implements Search {

    public static void main(String[] args) {
        BinarySearch binarySearch = new BinarySearch();
        int[] x = new int[] {
                2, 3, 5, 7, 10, 11, 18, 19, 23
        };
        boolean result = binarySearch.search(x, 3);
        System.out.println(result);
    }

    @Override
    public boolean search(int[] x, int key) {
        if (x == null)
            throw new NullPointerException("数组对象不能为空");
        if (x.length == 1 && key == x[0])
            return true;
        int left = 0;
        int right = x.length - 1;
        int middle = 0;
        while (left <= right) {
            long sum = right + left;
            middle = (int)(sum / 2);
            if (key > x[middle])
                left = middle + 1;
            else if (key < x[middle])
                right = middle - 1;
            else
                return true;
        }
        return false;
    }
}

注意:应该考虑到int溢出的情况。当求数组中间位置时,如果数组长度很大,则(right + left)/ 2中的right + left容易溢出,所以先将和放入long类型的sum中,然后再除2后转换为int类型,因为中间索引一定在int所允许的范围内。
具体代码体现在

long sum = right + left;
middle = (int)(sum / 2);
点赞