1.4.10修改二分查找算法,使之总是返回和被查找的键匹配的索引最小元素(且仍然能够保证对数级别的运行时间)。
答: 以下代码rankMin。
import java.util.Arrays;
public class BinarySearch
{
public static int rank(int key,int[]a)
{
int lo=0;
int hi=a.length-1;
int keyIndex=-1;
while (lo<=hi)
{
int mid=lo+(hi-lo)/2;
if (key<a[mid]) hi=mid-1;
else if(key>a[mid]) lo=mid+1;
else return mid;
}
return keyIndex;
}
public static int rankMin(int key,int[]a)
{
int lo=0;
int hi=a.length-1;
int keyIndex=-1;
while (lo<=hi)
{
int mid=lo+(hi-lo)/2;
if (key<a[mid]) hi=mid-1;
else if(key>a[mid]) lo=mid+1;
else
{
keyIndex=mid;
hi=mid-1;
}
}
return keyIndex;
}
public static int rankMax(int key,int[]a)
{
int lo=0;
int hi=a.length-1;
int keyIndex=-1;
while (lo<=hi)
{
int mid=lo+(hi-lo)/2;
if (key<a[mid]) hi=mid-1;
else if(key>a[mid]) lo=mid+1;
else
{
keyIndex=mid;
lo=mid+1;
}
}
return keyIndex;
}
public static void main(String[] args)
{
int[] whitelist=In.readInts(args[0]);
int key=Integer.parseInt(args[1]);
Arrays.sort(whitelist);
StdOut.println("Key rank index is:"+ rank(key,whitelist));
StdOut.println("Key rankMin index is:"+ rankMin(key,whitelist));
StdOut.println("Key rankMax index is:"+ rankMax(key,whitelist));
}
}
答: 以下代码rankMin。
![图片](https://i-blog.csdnimg.cn/blog_migrate/8071125dc9df268386fa45077e3c11d0.png)
import java.util.Arrays;
public class BinarySearch
{
public static int rank(int key,int[]a)
{
int lo=0;
int hi=a.length-1;
int keyIndex=-1;
while (lo<=hi)
{
int mid=lo+(hi-lo)/2;
if (key<a[mid]) hi=mid-1;
else if(key>a[mid]) lo=mid+1;
else return mid;
}
return keyIndex;
}
public static int rankMin(int key,int[]a)
{
int lo=0;
int hi=a.length-1;
int keyIndex=-1;
while (lo<=hi)
{
int mid=lo+(hi-lo)/2;
if (key<a[mid]) hi=mid-1;
else if(key>a[mid]) lo=mid+1;
else
{
keyIndex=mid;
hi=mid-1;
}
}
return keyIndex;
}
public static int rankMax(int key,int[]a)
{
int lo=0;
int hi=a.length-1;
int keyIndex=-1;
while (lo<=hi)
{
int mid=lo+(hi-lo)/2;
if (key<a[mid]) hi=mid-1;
else if(key>a[mid]) lo=mid+1;
else
{
keyIndex=mid;
lo=mid+1;
}
}
return keyIndex;
}
public static void main(String[] args)
{
int[] whitelist=In.readInts(args[0]);
int key=Integer.parseInt(args[1]);
Arrays.sort(whitelist);
StdOut.println("Key rank index is:"+ rank(key,whitelist));
StdOut.println("Key rankMin index is:"+ rankMin(key,whitelist));
StdOut.println("Key rankMax index is:"+ rankMax(key,whitelist));
}
}