class HalfSearch
{
public static void main(String[] args)
{
int[] arr=new int[]{1,2,3,4,5,6,7,8,9};
int index;
index=halfsearch_1(arr,10);
System.out.println("index="+index);
}
// 折半查找:
public static int halfsearch(int[] a,int result)
{
int min=0,max=a.length-1;
int mid=(min+max)/2;//或者用(min+max)>>1;
while(a[mid]!=result)
{
if (result>a[mid])
min=mid+1;
else
max=mid-1;
if(min>max)
return -1;
mid=(min+max)/2;
}
return mid;
}
// 另一种折半查找:
public static int halfsearch_1(int[] a,int result)
{
int min=0,max=a.length-1;
while(min<=max)
{
int mid=(min+max)/2;
if(result>a[mid])
min=mid+1;
else if(result<a[mid])
max=mid-1;
else
return mid;
}
return -1;
}
// 练习:有一个有序的数组,想要将一个元素插入到该数组中,并且插入后数组仍然是有序的。
public static int halfsearch_2(int[] a,int result)
{
int min=0,max=a.length-1;
while(min<=max)
{
int mid=(min+max)/2;
if(result>a[mid])
min=mid+1;
else if(result<a[mid])
max=mid-1;
else
return mid;
}
return min;
}
}
|
|