java 简单搜索算法

 --无序查找
public static int Search(int[] a,int key){
for(int i=0;i<a.length;i++){
if(key==a[i]){
return i;
}
}
return -1;
}
 --折半查找
public static int BinarySearch(int[] a,int key){
int min,max,mid;
min=0;
max=a.length-1;
mid =(min+max)/2;
while(key!=a[mid]){
if(key>a[mid]){
min=mid+1;
}else{
max=mid-1;
}
if(max<min)
return -1; mid=(min+max)/2;
}
return mid;
}
 --折半查找优化
public static int BinarySearch_2(int[] a,int key){
int min,max,mid;
min=0;
max=a.length-1;
while(max>=min){
mid =(min+max)>>1;
if(key>a[mid]){
min=mid+1;
}else if(key<a[mid]){
max=mid-1;
}else{
return mid;
}
}
return -1;
}
上一篇:Bzoj3144 [Hnoi2013]切糕


下一篇:MySQL数据库学习初步