欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2021-03-18

程序员文章站 2024-03-22 18:16:58
...

二分查找:
package demo05;

public class erfen {
public static void main(String[] args) {
int[] arr={1,3,5,7,9};
int key=7;
int i = binarySearch(arr, key);
System.out.println(i);

}
public static int binarySearch(int[] arr1, int key){

    int min=0;
    int max=arr1.length-1;
    while(min<=max){
        //中间索引
        int mid=(min+max)/2;
        if(key > arr1[mid]){
            min = mid+1;
        }else if(key < arr1[mid]){
            max = mid-1;
        }else{
            return mid;
        }
    }
    return -1;
}

}

运行结果:
2021-03-18

推荐阅读