二分查找法java实现
二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。
算法要求
查询指定数组arr中指定元素t。
public static int side(int t,int[] arr){
int max=arr.length-1;
int min=0;
int side=(max+min+1)/2;
int i=0;
while (t!=arr[side]&&max!=min){
if(t>arr[side]){
min=side;
side=(max+min+1)/2;
}else {
max=side;
side=(max+min+1)/2;
}
}
if(max==min){
if(t!=arr[min])
System.out.println("未查找到");
}
return t;
}
查询指定范围(min,max)内的元素t。
public static int side(int max,int min,int t){
int side=(max+min+1)/2;
int i=0;
while (t!=side&&max!=min){
if(t>side){
min=side;
side=(max+min+1)/2;
}else {
max=side;
side=(max+min+1)/2;
}
}
if(max==min&&max!=t){
System.out.println("未找到");
}
return t;
}