顺序查找+二分查找
程序员文章站
2022-03-13 22:44:44
...
1.顺序查找
public static int indexOf(int[]a,int v){
int ret=-1;
int i=0;
while(i<a.length){
if(a[i]==v)
ret=i;
i++;
}
return ret;
}
2.二分查找(左闭右闭)
public static int binarySearch(int a[],int v){
int ret=-1;
int left=0;
int right=a.length-1;
while(left<right){
int mid=(left+right)/2;
if(a[mid]==v)
ret=mid;
if(a[mid]>v)
right=mid-1;
else
left=mid+1;
}
return ret;
}