Search code examples
javaalgorithmbinary-searchredirectstandardoutput

About exercise 1.2.9 on p.115 in "Algorithms 4th Edition" by Robert Sedgewick and Kevin Wayne


I am reading "Algorithms 4th Edition" by Robert Sedgewick and Kevin Wayne.

The following code is my answer for the exercise 1.2.9 on p.115.

I expect this code prints the total number of keys examined during all searches but this code doesn't print the value of the counter.

Why?

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?
    }

}

Solution

  • StdIn will never be empty. It's your keyboard, it can only be waiting for your input. You need to add something to end the loop, such as the user entering some specific key, like q or some other key that won't affect the function of the rest of your program.