THINK FIRST·CODE LATER

← All labs

How many times does it occur? Two binary searches

Problem

In a sorted array with repeated values, count the occurrences of a key in O(log n) — without scanning the run of equal values.

Write CountOccurrences with a recursive lowerBound(a, key, low, high) that returns the index of the first element ≥ key in a[low..high−1] (or high if there is none), counting one probe per element examined. Then count = lowerBound(key + 1) − lowerBound(key). Read n, the n sorted values, and keys until the end of input.

For the input

10
1 3 3 3 5 5 8 8 8 8
3 8 4 1 9

the program prints

3: 3 time(s), indexes 1..3 (8 probes)
8: 4 time(s), indexes 6..9 (7 probes)
4: absent, would be inserted at index 4 (8 probes)
1: 1 time(s), indexes 0..0 (8 probes)
9: absent, would be inserted at index 10 (6 probes)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d7-6-data-1.txt

10
1 3 3 3 5 5 8 8 8 8
3 8 4 1 9
What your program must print for d7-6-data-1.txt
3: 3 time(s), indexes 1..3 (8 probes)
8: 4 time(s), indexes 6..9 (7 probes)
4: absent, would be inserted at index 4 (8 probes)
1: 1 time(s), indexes 0..0 (8 probes)
9: absent, would be inserted at index 10 (6 probes)

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d7-6-data-1.txt

Windows PowerShell does not understand <:

Get-Content d7-6-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.