【数据结构】【折半查找法】【二分查找法】Java代码


public class half {
    public static int find(int[] nums,int num){
        int max=nums.length-1;
        int min=0;
        int mid=-1;
        while(min<=max){
            mid=(max+min)/2;
            if(nums[mid]>num){
                max=mid-1;
            }else if(nums[mid]<num){
                min=mid+1;
            }else if(nums[mid]==num){
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums={1,2,5,7,9};
        System.out.println(find(nums,5));
    }
}

相关视频:
Java 二分查找法

posted @ 2021-12-29 14:36  萌狼蓝天  阅读(183)  评论(0编辑  收藏  举报