折半查找:提高效率,但是必须保证是有序的数组。
第一种方式:
class Shuzu
{
public static void main(String[] args)
{
int[] arr={1,3,5,7,9,11};
int index=halfSearch(arr,3);
System.out.println("index="+index);
}
public static int halfSearch(int[] arr,int key)
{
int min,mid,max;
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=(min+max)/2;
}
return mid;
}
}
*/
/*第二种方式:
class Shuzu
{
public static void main(String[] args)
{
int[] arr={1,3,5,7,9,11};
int index=halfSearch_2(arr,11);
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=(min+max)>>1; //(相当于mid=(min+max)/2;
if(key > arr[mid])
min=mid+1;
else if(key < arr[mid])
max=mid-1;
else
return mid;
}
return -1;
}
} |
|