二分查找 BinarySearch

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32767041/article/details/86098066

二分查找算法

前提条件

数组有序

时间复杂度

二分搜索方法充分利用了元素间的次序关系,采用分治策略,可在最坏情况下用 O ( l o g n ) O(logn) 时间完成搜索任务

基本思想

将n个元素分成个数大致相同的两半,取a[n/2]与x进行比较。
如果x=a[n/2],则找到x,算法终止。
如果x<a[n/2], 则只要在数组a的左半部继续搜索x。
如果x>a[n/2],则只要在数组a的右半部继续搜索x。

算法实现

  • 非递归
public static int binarySearch(int[] arr, int target) {
    if (arr == null || arr.length == 0) return -1;

    int left = 0, right = arr.length - 1;
    while (left <= right) {
        int mid = (left + right) / 2;
        if (arr[mid] == target) return mid;
        else if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}
  • 递归
public static int binarySearch2(int[] arr, int target, int left, int right) {
    if (arr == null || arr.length == 0) return -1;
    
    if (left <= right) {
        int mid = (left + right) / 2;
        if (arr[mid] == target) return mid;
        if (arr[mid] < target) return binarySearch2(arr, target, mid + 1, right);
        else return binarySearch2(arr, target, left, mid - 1);
    }
    return -1;
}

猜你喜欢

转载自blog.csdn.net/qq_32767041/article/details/86098066
今日推荐