- 用于有序数组
- low,high,middle = (low + hight) / 2
- 如果arr(middle) > value,则high = middle - 1,否则 high = middle + 1
重复以上过程,直到arr(middle) = value
代码实现:
public static int binary(int[] array, int value)
{
int low = 0;
int high = array.length - 1;
while(low <= high)
{
int middle = (low + high) / 2;
if(value == array[middle])
{
return middle;
}
if(value > array[middle])
{
low = middle + 1;
}
if(value < array[middle])
{
high = middle - 1;
}
}
return -1;
}
网友评论