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

Java折半查找算法

程序员文章站 2024-03-01 14:34:22
...

折半查找

import java.util.Arrays;
/**
 * 折半查找
 */
public class Test2 {
    public static void main(String[] args) {
        long[] longs1={25,21,41,58,45,78,89,56,25,12,23,14};
        Arrays.sort(longs1);
        System.out.println(Arrays.toString(longs1));
        System.out.println(banirySearch(21, longs1));
        System.out.println(banirySearch(13, longs1));;
    }

    /**
     * 折半查找
     * @param target 目标元素
     * @param arr 范围数组
     * @return 找到返回索引,否则返回-1
     */
    public static int banirySearch(long target ,long[] arr){
        int head = 0;
        int end = arr.length-1;
        int mid;
        while(head<=end){
            mid = (head+end)/2;
            if(target==arr[mid]){
                return mid;
            }
            if (target>arr[mid]){
                head = mid+1;
            }else {
                end = mid-1;
            }
        }
        return -1;
    }
}

结果

[12, 14, 21, 23, 25, 25, 41, 45, 56, 58, 78, 89]----21
2
-1