Algs4-1.4.10二分查找找出元素所在的最小索引
1.4.10修改二分查找算法,使之总是返回和被查找的键匹配的索引最小元素(且仍然能够保证对数级别的运行时间)。
答: 以下代码rankMin。
![图片](http://r.photo.store.qq.com/psb?/f33bb27a-608a-4097-811a-86bbde18cf7a/ldLczBbuiYGp03KZzgcP29Lp.T*Om5S1cp.igRGjkpI!/o/dPYAAAAAAAAA&ek=1&kp=1&pt=0&bo=9wETAfcBEwEDACU!&tl=1&su=0192628785&tm=1540515600&sce=0-12-12&rf=2-9)
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。
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));
}
}