/**
* 二分查找法
* @author lhever_ 2016年7月23日 下午10:05:48
* @version v1.0
*/
public class BinarySearch
{
/**
* 查找指定整数在数组中的索引位置,找不到则返回-1;
* @param key
* @param a
* @return int
* @author lihong 2016年7月23日 下午10:26:14
* @since v1.0
*/
public static int rank(int key, int[] a)
{
// 数组必须是有序的
int low = 0;
int high = a.length - 1;
while (low <= high)
{
// 被查找的键(数值)要么不存在,要么必然存在于a[low .... high]之中
int mid = low + (high - low) / 2;
if (key < a[mid])
{
high = mid - 1;
}
else if (key > a[mid])
{
low = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
/**
* 测试
* @param args void
* @author lhever_ 2016年7月23日 下午10:18:27
* @since v1.0
*/
public static void main(String... args)
{
int[] testArray = new int[] {-3, 0, 5, 8, 9, 100};
Arrays.sort(testArray);
System.out.println(Arrays.toString(testArray));
System.out.println(rank(-3, testArray));
System.out.println(rank(100, testArray));;
}
}
每日一省之————二分查找法demo
最新推荐文章于 2023-02-28 16:14:55 发布