ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

有序数组二分查找法

2022-07-28 12:31:58  阅读:42  来源: 互联网

标签:二分 arr target int binarySearch 查找 static result 数组


有序数组二分查找法:

方式1,while循环:

public class BinarySearchTest {
    public static void main(String[] args) {
        int[] arr = {1,3,4,7,8,11,15,19,44,48,49};
        int target = 50;
        int result = binarySearch(target,arr);
        System.out.println("result:" + result);
    }

    private static int binarySearch(int target, int[] arr) {
        int l = 0,r = arr.length - 1,m;
        while(l<=r){
            m = (l + r) >> 1;
            if(arr[m] == target){
                return target;
            }
            if(arr[m] > target){
                r = m - 1;
            }
            if(arr[m] < target){
                l = m + 1;
            }
        }
        return -1;
    }
}

方式2,递归:

public class BinarySearchDiGuiTest {
    public static void main(String[] args) {
        int[] arr = {1,3,4,7,8,11,15,19,44,48,49};
        int target = 2;
        int result = binarySearch(target,arr);
        System.out.println("result:" + result);
    }

    private static int binarySearch(int target, int[] arr) {
        int l = 0,r = arr.length - 1,m = 0;
        int result = search(l,r,m,arr,target);
        return result;
    }

    private static int search(int l, int r, int m,int[] arr,int target) {
        m = (l + r) >> 1;
        if(arr[m] == target){
            return target;
        }
        if(arr[m] > target){
            r = m - 1;
        }
        if(arr[m] < target){
            l = m + 1;
        }
        if(l <= r){
            return search(l,r,m,arr,target);
        }
        return -1;
    }
}

算法理解思路很重要。

 

标签:二分,arr,target,int,binarySearch,查找,static,result,数组
来源: https://www.cnblogs.com/super-chao/p/16528219.html

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有