7、二分查找

2023-03-31  本文已影响0人  RobertLiu123

数组中有元素5,18,23,37,48,65,78,85,97,请找出85的位置
二分查找必须满足条件:
1、所有元素要么递增要么递减
2、每次只找一个元素

//普通查找
    public static int getIndex(int targt,int[] arr){
        int index = -1;
        int count = 0;
        for(int i = 0;i < arr.length;i++){
            count++;
            if(arr[i] == targt){
                index = i;
                break;
            }
        }
        System.out.println("执行了" + count +"次循环");
        return index;
    }
//二分查找
    public static int binarySearch(int targt,int[] arr){
        int left = 0;
        int right = arr.length - 1;
        int index = 0;
        int count = 0;
        while(left <= right){
            count++;
            int mid = (left + right) / 2;
            if(targt > arr[mid]){
                left = mid + 1;
            }else if(targt < arr[mid]){
                right = mid - 1;
            }else{
                index = mid;
                break;
            }
        }
        System.out.println("执行了" + count +"次循环");
        return index;
    }
上一篇 下一篇

猜你喜欢

热点阅读