代码实现:
class HalfSearch
{
public static void main(String[] args)
{
int[] arr = new int[]{1,5,9,12,15,25,45,75,89,92,94,96}//定义一组已排序的数组
int num = 96; //需要查找的数
int index = halfSearch(arr,num);
String s = (index!=-1)?"在数组中.":"不在数组中.";
System.out.println(num+s+"index="+index);
}
private static int halfSearch(int[] arr,int num)
{
int min = 0;
int max = arr.length-1;
int mid = 0;
while (min<=max)
{
mid = (min+max)/2;
if (arr[mid]>num)
{
max = mid - 1;
}
else if (arr[mid]<num)
{
min = mid + 1;
}
else
{
return mid; //数组中找到该数
}
}
return -1; //数组中未找到该数
}
}
结果显示: