package com.zgz;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* 二分查找
*
* @author guozhenZhao
* @date 2019年4月8日
*/
public class BinarySearch {
/**
* 要查找的数组必须是有序的
* @param key
* @param arr
* @return
*/
public static int rank(int key, int[] arr) {
int lo = 0;
int hi = arr.length - 1;
//被查找的键存在于arr[lo]-arr[hi]之间
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (key < arr[mid])
hi = mid - 1;
if (key > arr[mid])
lo = mid + 1;
else
return mid;
}
return -1;
}
public static void main(String[] args) {
int[] whiteList = {2,4,5,3,8,9,7,6};
Arrays.sort(whiteList);
int key = 10;
System.out.println(rank(key, whiteList));
}
}
原文:https://blog.51cto.com/13416247/2375431