查找算法-二分法

1 原理和步骤

有序数组插入和删除操作中,由于所有靠后的数据都需要移动以腾开空间,所以速度较慢。在查找方面,无序数组是通过线性查找,而有序数组可以通过二分法进行快速查找,速度比无序数组快很多。
二分法的时间复杂度为0(log n),具体步骤是先查看数组正中间的数据项,如果那个数据项比要找的大,就要缩小范围,在数组的前半段进行查找;反之则在后半段找。反复这个过程即可。

2完整代码

/**
 * 二分查找
 * 
 * @author JayLai
 * @version 1.0
 * @date 2017年12月29日 12:56
 *
 */
public class binarysearch {

    private int[] arr; // 初始化数组

    /**
     * 构造函数
     */
    public binarysearch(int size) {
        this.arr = new int[size]; // 初始化数组
        for (int i = 0; i < arr.length; i++) { // 录入有序数组
            arr[i] = i;
        }
    }

    public int find(int value) {

        int firstIndex = 0; // 起始下标
        int lastIndex = arr.length - 1; // 末端下标
        int middleIndex = (lastIndex + firstIndex) / 2; // 中间项下标

        while (value != arr[middleIndex]) {

            /*
             * firstIndex <= (firstIndex+ lastIndex)/2 < lastIndex
             */
            if (middleIndex == lastIndex - 1) {
                if (value == arr[lastIndex]) {
                    return lastIndex;
                } else {
                    return -1;
                }
            } else if (value > arr[middleIndex]) { // 目标数据大于数组中间项
                firstIndex = middleIndex;
                middleIndex = (lastIndex + firstIndex) / 2;
            } else { // 目标数据小于数组中间项
                lastIndex = middleIndex;
                middleIndex = (lastIndex + firstIndex) / 2;
            }
        }

        return middleIndex; // 返回查询元素的下标
    }

    public static void main(String[] args) {
        binarysearch search = new binarysearch(100);
        System.out.println(search.find(99));
        System.out.println(search.find(0));
        System.out.println(search.find(200));
    }

}

3 测试结果

这里写图片描述

4 参考文献

[1] Robert, Lafore., Java数据结构和算法.第2版 版. 2004: 中国电力出版社.
[2] Sedgewick Robert与Wayne  Kevin., 算法. 2012: 人民邮电出版社.
原创文章 32 获赞 12 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_35469756/article/details/79102998