四、查找和进制转换实例
1、折半查找
提高查找效率,但是必须保证该数组是有序数组
public static int halfSearch_1(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
max=mid-1;
if(min>max)
return -1;
mid=(min+max)/2;
}
}
public static int halfSearch_2(int arr[],int key)
{
int min=0,max=arr.length-1,mid;
while(min<=max)
{
mid=(min+max)>>1;
if(key>arr[mid])
min=mid+1;
else if
max=mid-1;
else
return min;
}
return -1;
}
2、十进制—二进制
public static void toBin(int num)
{
StringBuffer sb = new StringBuffer();
while(num>0)
{
sb.append(num%2);
num=num/2;
}
System.out.println(sb.reverse());
}
|