Binary Search

作者: 几千里也 | 来源:发表于2017-11-15 13:51 被阅读13次
    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 : "找不到数值"); 
        }
    }
    

    相关文章

      网友评论

        本文标题:Binary Search

        本文链接:https://www.haomeiwen.com/subject/acwcvxtx.html