CECS 277
LAB ASSIGNMENT #6
Assigned date: 4/6
Due date: 4/13
30 points
1. [3 points] Implement a generic version of the binary search algorithm.
/**
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;
}
}
2. [10 points] Rewrite the problem 2 in the lab assignment 4 by implementing the following methods:
3. [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");
}
}
4. [7 points] Turn the HashSet implementation of chapter 16 into a generic class. Use an array list instead of an array to store the buckets.
Here is the links to th files HashSet.java and HashSetDemo.java in the chapter 16.