1.2.9修改BinarySearch(请见1.1.10.1节中的二分查找代码),使用Counter统计在有查找中被检查的键的总数并在查找全部结束后打印该值。提示:在main()中创建一个Counter对象并将它作为参数传递给rank()。
答:
BinarySearch Code:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
int[] whitelist=In.readInts(args[0]);
Arrays.sort(whitelist);
Counter counterKey=new Counter("counterKey");
while (!StdIn.isEmpty())
{
int key=StdIn.readInt();
int indexOfWhite=rank(key,whitelist,counterKey);
}
StdOut.printf("BinarySearch check Key Counter is:%d ",counterKey.tally());
}//end main
public static int rank(int key,int[] a,Counter counterKey)
{
int lo=0;
int hi=a.length-1;
while(lo<=hi)
{
counterKey.increment();
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 -1;
}
}//end class Test
////////////////////////////////////
Counter Code:
public class Counter
{
private final String name;
private int count;
public Counter(String id)
{
name=id;
count=0;
}
public void increment()
{
count++;
}
public int tally()
{
return count;
}
public String ToString()
{
return count+ " " +name;
}
public static void main(String[] args)
{
Counter heads=new Counter("heads");
Counter tails=new Counter("tails");
heads.increment();
heads.increment();
tails.increment();
StdOut.println(heads+" " + tails);
StdOut.println(heads.tally() + tails.tally());
}
}
答:
BinarySearch Code:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
int[] whitelist=In.readInts(args[0]);
Arrays.sort(whitelist);
Counter counterKey=new Counter("counterKey");
while (!StdIn.isEmpty())
{
int key=StdIn.readInt();
int indexOfWhite=rank(key,whitelist,counterKey);
}
StdOut.printf("BinarySearch check Key Counter is:%d ",counterKey.tally());
}//end main
public static int rank(int key,int[] a,Counter counterKey)
{
int lo=0;
int hi=a.length-1;
while(lo<=hi)
{
counterKey.increment();
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 -1;
}
}//end class Test
////////////////////////////////////
Counter Code:
public class Counter
{
private final String name;
private int count;
public Counter(String id)
{
name=id;
count=0;
}
public void increment()
{
count++;
}
public int tally()
{
return count;
}
public String ToString()
{
return count+ " " +name;
}
public static void main(String[] args)
{
Counter heads=new Counter("heads");
Counter tails=new Counter("tails");
heads.increment();
heads.increment();
tails.increment();
StdOut.println(heads+" " + tails);
StdOut.println(heads.tally() + tails.tally());
}
}