THINK FIRST·CODE LATER

← All labs

Linear versus binary search, in comparisons

Problem

Write SearchCompare. Read n and build the sorted array 1, 4, 7, … (a[i] = 3i + 1). For each key until the end of input, run a linear search and a binary search, both counting key comparisons (one per array element examined), and print the index found (−1 if absent) and both counts. Then print the totals and the worst case of binary search for this n (the number of times n can be halved until 0).

State the loop invariant of your binary search in a comment.

For the input

1000 1 2998 1501 5 2999

the program prints

Array: 1000 sorted values from 1 to 2998
key 1: index 0, linear 1, binary 9
key 2998: index 999, linear 1000, binary 10
key 1501: index 500, linear 501, binary 9
key 5: index -1, linear 1000, binary 10
key 2999: index -1, linear 1000, binary 10
Total comparisons: linear 3502, binary 48
Binary search worst case for n = 1000: 10 comparisons

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.

d6-4-data-1.txt

1000 1 2998 1501 5 2999
What your program must print for d6-4-data-1.txt
Array: 1000 sorted values from 1 to 2998
key 1: index 0, linear 1, binary 9
key 2998: index 999, linear 1000, binary 10
key 1501: index 500, linear 501, binary 9
key 5: index -1, linear 1000, binary 10
key 2999: index -1, linear 1000, binary 10
Total comparisons: linear 3502, binary 48
Binary search worst case for n = 1000: 10 comparisons

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 < d6-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content d6-4-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.