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

简单算法之二分查找

程序员文章站 2022-03-08 23:28:28
...
package com.chasen;

public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 10, 2, 5, 8, 18, 30};
        int number = 2;
        int index = binarySearch(arr, number);
        System.out.println(index);
    }

    private static int binarySearch(int[] arr, int number) {
        int min = 0;
        int max = arr.length - 1;
        while (min <= max) {
            int mid = (min + max) >> 1;
            if (arr[mid] > number) {
                max = mid - 1;
            } else if (arr[mid] < number) {
                min = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

}

 

相关标签: java