折半查找基本思想:
假设有序表按关键码升序排列,取中间记录作为比较对象,若给定值与中间记录相等,则查找成功;若给定值小于中间记录,则在有序表的左半区继续查找;若给定值大于中间记录,则在有序表的右半区继续查找。不断重复上述过程,知道查找成功或者查找区域无记录,查找失败。
private static <T extends Comparable<T>>
int binarySearch(T[] src, T key)
{
int low = 0;
int high = src.length - 1;
int middle = low + (high - low) / 2;
while (low <= high)
{
int compare = key.compareTo(src[middle]);
if (compare == 0)
{
return middle;
}
else if (compare > 0)
{
low = middle + 1;
}
else if (compare < 0)
{
high = middle - 1;
}
middle = low + (high - low) / 2;
} return -1;
}
``、
**
折半查找性能分析:
**
查找成功时ASL=1/n(层数 * 层上节点个数)
查找失败时ASL=1/n(外部节点所在层数 * 层上外部节点个数)(包括根节点)