二分查找的递归和迭代形式
程序员文章站
2024-03-20 09:41:16
...
二分查找是基于有序数组的
public class test{
public int rank1(int key,int lo,int hi,int array[])//二分查找的递归形式
{
if(hi<lo)
return lo;
int mid = lo + (hi - lo ) /2;
int cmp = key-array[mid];
if(cmp<0)
return rank1(key,lo,mid-1,array);
else if(cmp>0)
return rank1(key,mid+1,hi,array);
else
return mid;
}
public int rank2(int key,int lo,int hi,int array[])//迭代方式
{
while (lo<=hi)
{
int mid=lo+(hi-lo)/2;
int cmp = key-array[mid];
if(cmp<0)
hi=mid-1;
else if(cmp>0)
lo=mid+1;
else
return mid;
}
return lo;
}
public static void main(String args[])
{
test t=new test();
int a[]={1,2,3,4,5,6,7,8,9};
int location1 = t.rank1(9,0,8,a);
int location2 = t.rank2(9,0,8,a);
System.out.println(location1);
System.out.println(location2);
}
}