Skip to content

二分查找

java
import java.util.Arrays;

/**
 * 二分查找
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {2, 4, 6, 7, 5, 2};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        System.out.println(rank(5, arr));
        System.out.println(rank(1000, arr));
    }
    public static int rank(int key, int[] arr) {
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (arr[mid] > key) {
                end = mid - 1;
            } else if (arr[mid] < key) {
                start = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}