二分法查找有序数组的两种方法

/**
* 二分法查找
*/

//方法一:算法实现
//定义类
//返回值类型:数组和需要查找(索引)的数值
public class BinarySearchUtils {
     
    public static int binarySearch(int[]array, int value){
     
        int start = 0;
        int end = array.length -1;
        while (true){
     
            int mid = (start + end)/2;
            int midValue = array[mid];

            if (value == midValue) {
     
                return mid;
            } else {
     
                if (midValue > value){
     
                    end = mid - 1;
                } else {
     
                    start = mid + 1;
                }
            }
            if (start > end) {
     
                return -1; //判断失效,返回-1
            }
        }
    }
}

//调用类
public class TestBinarySearchUtils {
     
    public static void main(String[] args) {
     
        int [] array = {
     1,3,5,7,9};
        int index1 = BinarySearchUtils.binarySearch(array, 7);
        System.out.println(index1);
    }
}
//索引为:3


//方法二:直接调用 Arrays下的 binarySearch()方法,若找不到给定数值,返回其应在插入点的信息(详见注释)
import java.util.Arrays;

public class Demo {
     
    public static void main(String[] args) {
     
        int [] arr = {
     2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32};
        int a = Arrays.binarySearch(arr, 15);
        int b = Arrays.binarySearch(arr, 20);

        int c = Arrays.binarySearch(arr, 1,4,5);
        int d = Arrays.binarySearch(arr, 2,4,6);
        int e = Arrays.binarySearch(arr, 12,14,16);
        int f = Arrays.binarySearch(arr, 14,15,16);
        int g = Arrays.binarySearch(arr, 20,22,32);

        //不指定范围检索
        System.out.println(a); // -8 返回:-索引值
        System.out.println(b); // 9

        //指定范围检索
        System.out.println(c); //-3,在范围内,但不是数组元素,返回:-索引值
        System.out.println(d); //2,在范围内
        System.out.println(e); //-13,索引值范围在数组个数-1范围内,但值不在指定索引范围  返回:–(fromIndex + 1)
        System.out.println(f); //-15,索引值范围在数组个数-1范围内,但值不在指定索引范围  返回:–(fromIndex + 1)
        System.out.println(g); //报错,索引值范围超出数组个数-1,报错信息:Array index out of range
        
    }
}

你可能感兴趣的:(Java,二分法,二分法,算法,java)