Lab 08

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development

Set up environment

Folder Structure

Your intelij project directory should look something like the following:

Lab08
|-- out
`-- src
    |-- ArraySetTester.java
    |-- LinkedSetTester.java
    `-- Tester.java

Create Files

Here are the files you are to create:

  • Set.java (interface) remember: isEmpty is a default method
  • ArraySet.java
  • Node.java
  • LinkedSet.java

The only module you are allowed to import (but you don’t have to) java.util.Objects;

Helper methods

In addition to implementing the public contains method, it is helpful to implement private search methods for both the ArraySet (returns the index of the item) and the LinkedSet (returns the searched node) classes.

Runtime questions

At the top of Set.java, below your names, add a comment that answers the following questions. For each method, give the worst-case big-O runtime for both ArraySet and LinkedSet, in terms of \(n\) (the number of items in the set), along with a one-sentence explanation.

Runtime questions

  1. contains
  2. add (Be careful! Think about everything add has to do before it can actually add the item. For ArraySet, you may give the amortized runtime and say so.)
  3. remove
  4. size
  5. Both implementations keep items in insertion order and both must check for duplicates. Based on your answers above, is either implementation clearly faster than the other for a set? Explain in 2-3 sentences. What would need to change about our design to make contains faster than \(O(n)\)?

Runtime questions

A table inside a block comment is a perfectly fine format:

/*
 * Runtime analysis
 *
 * method    | ArraySet | LinkedSet | explanation
 * ----------+----------+-----------+------------------------------
 * contains  |   O(?)   |   O(?)    | ...
 * ...
 */

Javadoc

Key Rules:

  • Starts with /** and ends with */
  • First sentence is a short summary — it appears in the generated HTML overview
  • @param tag should be listed for every parameter

Javadoc

   /**                                                                               
   * Calculates the average of an array of test scores.
   * Returns 0 if the array is null or empty.    
   *              
   * @param scores  an array of test scores, each in the range [0, 100]
   * @param count   the number of scores in the array
   * @return        the average of all scores, or 0 if the array is null or empty
   * @throws        IllegalArgumentException if count is negative
   *
   * @author        Adriana Picoral
   * @version       1.0
   */
  public double calculateAverage(double[] scores, int count) {
      if (scores == null || scores.length == 0) return 0;
      if (count < 0) throw new IllegalArgumentException("Count cannot be negative");

      double sum = 0;
      for (double score : scores) {
          sum += score;
      }
      return sum / count;
  }