Dynamic Arrays and Amortized Analysis

Nathan Sprague

List ADT

zyBook

Operation Description
Append(list, x) Inserts x at end of list
Prepend(list, x) Inserts x at start of list
InsertAfter(list, w, x) Inserts x after w
Remove(list, x) Removes x
Search(list, x) Returns item if found, else returns null
IsEmpty(list) Returns true if list has no items
GetLength(list) Returns the number of items in the list

Java Collections Framework

List Interface

Dynamic Arrays

Socrative Quiz

Evaluate the big-\(\Theta\) running time of the following methods.

  public static double searchAll(ArrayList<Integer> numbers) {
      long locSum = 0;
      for (int num : numbers) {
          locSum += numbers.indexOf(num);
      }
      return locSum / numbers.size();
  }

  public static void removeAll(ArrayList<Integer> numbers) {
      for (int i = 0; i < numbers.size(); i++) {
          numbers.remove(0); // remove element at index 0.
      }
  }
  1. searchAll: \(\Theta(n)\), removeAll: \(\Theta(n)\)
  2. searchAll: \(\Theta(n^2)\), removeAll: \(\Theta(n)\)
  3. searchAll: \(\Theta(n)\), removeAll: \(\Theta(n^2)\)
  4. searchAll: \(\Theta(n^2)\), removeAll: \(\Theta(n^2)\)

ArrayList append/add Analysis

ArrayList add Analysis

ArrayList add Analysis

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

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)?