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

Binary Search

程序员文章站 2022-05-05 17:46:11
...
public class Search {
    public static int binary(int[] number, int destination) {
        int start = 0;
        int end = number.length - 1;

        while (start <= end) {
            int middle = (start + end) / 2;
            if (number[middle] == destination) {
                return middle; // found
            } else if (number[middle] < destination) {
                start = middle + 1;
            } else if (number[middle] > destination) {
                end = middle - 1;
            }
        }

        return -1; // not found
    }
    
    public static void main(String[] args) {
        int[] number = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
        int find = Search.binary(number, 42);
        System.out.println(find >= 0 ? "找到数值于索引 " + find : "找不到数值"); 
    }
}