THINK FIRST·CODE LATER

← All labs

One search for every comparable type

Problem

Write GenericSearch with two generic methods that work on an array of any type whose elements can be compared:

public static <E extends Comparable<E>> int linearSearch(E[] list, E key)
public static <E extends Comparable<E>> int binarySearch(E[] list, E key)   // the list is sorted

Count the calls to compareTo in both. The input has three lines: the type (int, double or word), the sorted elements, and the keys to look for. main builds an Integer[], a Double[] or a String[] and passes it to the same methods. For the input

int
2 4 7 10 11 45 50 59 60 66 69 70 79
11 70 5 2

the program prints

11: linear search 4 (5 comparisons), binary search 4 (3 comparisons)
70: linear search 11 (12 comparisons), binary search 11 (3 comparisons)
5: linear search -1 (13 comparisons), binary search -1 (4 comparisons)
2: linear search 0 (1 comparisons), binary search 0 (3 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.

d2-7-data-1.txt

int
2 4 7 10 11 45 50 59 60 66 69 70 79
11 70 5 2
What your program must print for d2-7-data-1.txt
11: linear search 4 (5 comparisons), binary search 4 (3 comparisons)
70: linear search 11 (12 comparisons), binary search 11 (3 comparisons)
5: linear search -1 (13 comparisons), binary search -1 (4 comparisons)
2: linear search 0 (1 comparisons), binary search 0 (3 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 < d2-7-data-1.txt

Windows PowerShell does not understand <:

Get-Content d2-7-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.