import java.util.Arrays;
public class ArratTest5 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr=new int[]{1,2,4,2,6,3,5,7,3,9};
//int index=getIndex(arr,11);
Arrays.sort(arr);
printArray(arr);
int index=halfSearch_2(arr,2);
System.out.println("index="+index);
}
//第二种半分算法
public static int halfSearch_2(int[] arr,int key)
{
int min=0,max=arr.length-1,mid;
while(min<=max)
{
mid=(max+min)/2;
if(key>arr[mid])
min=mid+1;
else if(key<arr[mid])
max=mid-1;
else return mid;
}
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(arr[mid]<key)
min=mid+1;
else if(key<arr[mid])
max=mid-1;
if(min>max)
return -1;
mid=(min+max)/2;
}
return mid;
}
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 void printArray(int[] arr)
{
System.out.print("[");
for(int x=0;x<arr.length;x++)
{
if(x!=arr.length-1)
System.out.print(arr[x]+", ");
else
System.out.println(arr[x]+"]");
}
}
}
折半查找
最新推荐文章于 2023-01-31 23:42:23 发布