CECS 277
LAB ASSIGNMENT #4
Assigned date: 3/13
Due date: Mon 3/20

20 points

1. [10 points] Make the Measurable interface below into a generic class. Provide a static method that returns the largest element of ArrayList<T> provided that the elements are instances of Measure<T>. Be sure to return the value of type T.

public interface Measurable

{ double getMeasure();

}

Test your program by running the following main method.

import java.util.ArrayList;

/**
This program demonstrates the Measurable class.
*/
public class MeasurableDemo
{
public static void main(String[] args)
{
ArrayList<MeasurableString> words = new ArrayList<MeasurableString>();
words.add(new MeasurableString("Mary"));
words.add(new MeasurableString("had"));
words.add(new MeasurableString("a"));
words.add(new MeasurableString("little"));
words.add(new MeasurableString("lamb"));
System.out.println("Largest word: " + Measurable.largest(words));
System.out.println("Expected: little");
}
}

2. [10 points] Implement a generic binanry search program with the following requirements:


/**
A class for executing binary searches through an array.
*/
public class BinarySearcher
{
private int[] a;

/**
Constructs a BinarySearcher.
@param anArray a sorted array
*/
public BinarySearcher(int[] anArray)
{
a = anArray;
}

/**
Finds a value in a sorted array, using the binary
search algorithm.
@param v the value to search
@return the index at which the value occurs, or -1
if it does not occur in the array
*/
public int search(int v)
{
int low = 0;
int high = a.length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
int diff = a[mid] - v;

if (diff == 0) // a[mid] == v
return mid;
else if (diff < 0) // a[mid] < v
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
}

GRADING