折半查找(二分查找)代码示例

折半查找又叫二分查找,它的前提是线性表中的记录必须是关键码有序(通常是从小到大有序),线性表必须采用顺序存储。

package org.example.demo;

/**
 * 折半查找,也叫二分查找,时间复杂度O(logn)
 */
public class BinarySearchTest {

    public static int search(int[] arr, int key) {
        if (arr == null || arr.length == 0)
            return -1;
        int low = 0, high = arr.length - 1, mid = high + low >>> 1, e;
        while ((e = arr[mid]) != key) {
            if (e > key)
                high = mid -1;
            else
                low = mid + 1;
            if (low > high)
                return -1;
            mid = high + low >>> 1;
        }
        return mid;
    }

    private static void testCase() {
        int[] arr = { 1, 2, 5, 8, 9, 11, 12, 13};
        int key = 1;
        System.out.println("index: " + search(arr, key));
    }

    private static void testCase1() {
        int[] arr = null;
        int key = 80;
        System.out.println("index: " + search(arr, key));
    }

    private static void testCase2() {
        int[] arr = {};
        int key = 80;
        System.out.println("index: " + search(arr, key));
    }

    public static void main(String[] args) {
        testCase();
        testCase1();
        testCase2();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值