package javastudy;
//定义功能 找到第一次出现的位置,-1代表不存在
//折半查找
public class Study14
{
public static void main(String[] args)
{
int[] arr ={1,2,5,6,7,9};
int index = getIndex(arr,20);
System.out.println(index);
}
public static int getIndex(int[] arr,int key)
{
for(int x=0;x<arr.length;x++)
{
if(arr[x]==key)
return x;
}
return -1;//没有找到的返回值
}
//折半查找
public static int halfSearch(int[] arr,int key)
{
int min,max,mid;
min = 0;
max = arr.length-1;
mid = (min+max)/2;
while(arr[mid]!=key)
{
if(key>arr[mid])
min = mid + 1;
else if(key<arr[mid])
max = mid - 1;
if(min>max)//判断是否超出范围
return -1;
mid = (max+min)/2;
}
return mid;
}
}
|
|