【发布时间】:2020-06-06 13:31:45
【问题描述】:
我正在阅读 Robert Sedgewick 和 Kevin Wayne 的“算法第 4 版”。
以下代码是我对第 115 页练习 1.2.9 的回答。
我希望这段代码打印所有搜索期间检查的键的总数,但这段代码不打印计数器的值。
为什么?
package exercise.chapter2.section2;
import java.util.Arrays;
import edu.princeton.cs.algs4.Counter;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Ex1_2_09 {
public static int indexOf(int[] a, int key, Counter c) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
// Key is in a[lo..hi] or not present.
c.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;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// read the integers from a file
In in = new In(args[0]);
int[] whitelist = in.readAllInts();
// sort the array
Arrays.sort(whitelist);
Counter c = new Counter("- the total number of keys examinded during all searches");
// read integer key from standard input; print if not in whitelist
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
if (indexOf(whitelist, key, c) == -1) {
StdOut.println(key);
}
}
StdOut.println(c); //I want to print c, but this code doesn't print it. Why?
}
}
【问题讨论】:
-
“不打印”是什么意思?
-
@Kayaman 对不起,我的英语很差。我的意思是“StdOut.println(c);”不打印 c 的值。
-
那它打印什么?
-
@Kayaman 它什么也不打印。我猜这个代码在 StdIn.isEmpty() == true 时终止。
标签: java algorithm binary-search redirectstandardoutput