Dynamic Arrays and Amortized Analysis

Nathan Sprague

List ADT

OpenDSA

// List class ADT. Generalize the element type using Java Generics.
public interface List<E> { // List class ADT
  // Remove all contents from the list, so it is once again empty
  public void clear();

  // Insert "it" at the current location
  // The client must ensure that the list's capacity is not exceeded
  public boolean insert(E it);

  // Append "it" at the end of the list
  // The client must ensure that the list's capacity is not exceeded
  public boolean append(E it);

  // Remove and return the current element
  public E remove() throws NoSuchElementException;

  // Set the current position to the start of the list
  public void moveToStart();

  // Set the current position to the end of the list
  public void moveToEnd();

  // Move the current position one step left, no change if already at beginning
  public void prev();

  // Move the current position one step right, no change if already at end
  public void next();

  // Return the number of elements in the list
  public int length();

  // Return the position of the current element
  public int currPos();

  // Set the current position to "pos"
  public boolean moveToPos(int pos);

  // Return true if current position is at end of the list
  public boolean isAtEnd();

  // Return the current element
  public E getValue() throws NoSuchElementException;
  
  // Tell if the list is empty or not
  public boolean isEmpty();
}

Java Collections Framework

List Interface

Question…

Dynamic Arrays

ArrayList append/add Analysis

ArrayList add Analysis

ArrayList add Analysis

Let’s time this to see if that gives any insight…

Reminder… Geometric Series

Socrative Quiz (Summation Review)

Cost of Append in Dynamic Array

Solving the Summation

\[ \begin{aligned} n + \sum_{i=0}^{\lceil \log_2 n \rceil-1} 2^{i} &=n + 2^{\lceil \log_2 n \rceil-1+1} - 1\\ &=n + 2^{\lceil \log_2 n \rceil} - 1 \\ &\leq n + 2^{ \log_2 n +1} - 1 \\ & = n + 2n - 1\\ &= 3n - 1 \leq 3n \end{aligned} \]

Amortized cost of append

Socrative Quiz…

You are performing a code review on the following Java method. This is part of the software that manages an automobile’s safety features. loggingList is an ArrayList that stores log messages that will eventually be saved to persistent storage. Which of the following is the most appropriate evaluation of this code?

public static void respondToCollision(Area area) {

    loggingList.add("Airbag Depolyed!");
    if (area == Area.FRONT)
        deployAirbag();
}
  1. LGTM
  2. Spelling error in log message.
  3. area == Area.FRONT should be area.equals(Area.FRONT)
  4. Efficiency issues could lead to loss of life.
  5. Problem with code style: Missing braces after if.

Bankers View (informal)

What about insert (not append)?