Deprecated: Creation of dynamic property wpdb::$categories is deprecated in /var/www/twodee/blog/wp-includes/wp-db.php on line 668

Deprecated: Creation of dynamic property wpdb::$post2cat is deprecated in /var/www/twodee/blog/wp-includes/wp-db.php on line 668

Deprecated: Creation of dynamic property wpdb::$link2cat is deprecated in /var/www/twodee/blog/wp-includes/wp-db.php on line 668

Deprecated: Return type of WP_Theme::offsetExists($offset) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-theme.php on line 554

Deprecated: Return type of WP_Theme::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-theme.php on line 595

Deprecated: Return type of WP_Theme::offsetSet($offset, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-theme.php on line 535

Deprecated: Return type of WP_Theme::offsetUnset($offset) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-theme.php on line 544

Deprecated: Return type of WP_REST_Request::offsetExists($offset) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/rest-api/class-wp-rest-request.php on line 960

Deprecated: Return type of WP_REST_Request::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/rest-api/class-wp-rest-request.php on line 980

Deprecated: Return type of WP_REST_Request::offsetSet($offset, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/rest-api/class-wp-rest-request.php on line 992

Deprecated: Return type of WP_REST_Request::offsetUnset($offset) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/rest-api/class-wp-rest-request.php on line 1003

Deprecated: Return type of WP_Block_List::current() should either be compatible with Iterator::current(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 151

Deprecated: Return type of WP_Block_List::next() should either be compatible with Iterator::next(): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 175

Deprecated: Return type of WP_Block_List::key() should either be compatible with Iterator::key(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 164

Deprecated: Return type of WP_Block_List::valid() should either be compatible with Iterator::valid(): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 186

Deprecated: Return type of WP_Block_List::rewind() should either be compatible with Iterator::rewind(): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 138

Deprecated: Return type of WP_Block_List::offsetExists($index) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 75

Deprecated: Return type of WP_Block_List::offsetGet($index) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 89

Deprecated: Return type of WP_Block_List::offsetSet($index, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 110

Deprecated: Return type of WP_Block_List::offsetUnset($index) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 127

Deprecated: Return type of WP_Block_List::count() should either be compatible with Countable::count(): int, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /var/www/twodee/blog/wp-includes/class-wp-block-list.php on line 199

Deprecated: Creation of dynamic property Automattic\Jetpack\Connection\Manager::$error_handler is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/vendor/automattic/jetpack-connection/src/class-manager.php on line 91

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Instagram_Gallery::$is_wpcom is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/class-wpcom-rest-api-v2-endpoint-instagram-gallery.php on line 23

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Mailchimp::$wpcom_is_wpcom_only_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/class-wpcom-rest-api-v2-endpoint-mailchimp.php on line 17

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Tweetstorm_Gather::$wpcom_is_wpcom_only_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/class-wpcom-rest-api-v2-endpoint-tweetstorm-gather.php on line 21

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Tweetstorm_Gather::$is_wpcom is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/class-wpcom-rest-api-v2-endpoint-tweetstorm-gather.php on line 22

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Gutenberg_Available_Extensions::$wpcom_is_site_specific_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/gutenberg-available-extensions.php on line 20

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Memberships::$wpcom_is_wpcom_only_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/memberships.php on line 23

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Memberships::$wpcom_is_site_specific_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/memberships.php on line 24

Deprecated: Creation of dynamic property WPCOM_REST_API_V2_Endpoint_Subscribers::$wpcom_is_wpcom_only_endpoint is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/_inc/lib/core-api/wpcom-endpoints/subscribers.php on line 15

Deprecated: Creation of dynamic property Automattic\Jetpack\Sync\Queue::$random_int is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/vendor/automattic/jetpack-sync/src/class-queue.php on line 38

Deprecated: Creation of dynamic property Automattic\Jetpack\Sync\Queue::$random_int is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/vendor/automattic/jetpack-sync/src/class-queue.php on line 38

Deprecated: Creation of dynamic property WPCOM_Widget_Goodreads::$shelves is deprecated in /var/www/twodee/blog/wp-content/plugins/jetpack/modules/widgets/goodreads.php on line 33

Deprecated: DateTime::__construct(): Passing null to parameter #1 ($datetime) of type string is deprecated in /var/www/twodee/blog/wp-includes/script-loader.php on line 348

Deprecated: Creation of dynamic property Advanced_Editor_Tools::$toolbar_classic_block is deprecated in /var/www/twodee/blog/wp-content/plugins/tinymce-advanced/tinymce-advanced.php on line 347

Deprecated: Creation of dynamic property Advanced_Editor_Tools::$toolbar_block is deprecated in /var/www/twodee/blog/wp-content/plugins/tinymce-advanced/tinymce-advanced.php on line 349

Deprecated: Creation of dynamic property Advanced_Editor_Tools::$toolbar_block_side is deprecated in /var/www/twodee/blog/wp-content/plugins/tinymce-advanced/tinymce-advanced.php on line 350

Deprecated: Creation of dynamic property Advanced_Editor_Tools::$panels_block is deprecated in /var/www/twodee/blog/wp-content/plugins/tinymce-advanced/tinymce-advanced.php on line 351

Deprecated: Creation of dynamic property Advanced_Editor_Tools::$used_block_buttons is deprecated in /var/www/twodee/blog/wp-content/plugins/tinymce-advanced/tinymce-advanced.php on line 354

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Block_Type::$plan_check is deprecated in /var/www/twodee/blog/wp-includes/class-wp-block-type.php on line 333

Deprecated: Creation of dynamic property WP_Term::$object_id is deprecated in /var/www/twodee/blog/wp-includes/class-wp-term.php on line 198

Deprecated: Creation of dynamic property WP_Term::$object_id is deprecated in /var/www/twodee/blog/wp-includes/class-wp-term.php on line 198

Deprecated: Creation of dynamic property WP_Term::$object_id is deprecated in /var/www/twodee/blog/wp-includes/class-wp-term.php on line 198
» CS 240: Lecture 7 – Amortized Analyis of ArrayList

teaching machines

CS 240: Lecture 7 – Amortized Analyis of ArrayList

September 8, 2021 by . Filed under
Deprecated: Creation of dynamic property WP_Term::$cat_ID is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 378

Deprecated: Creation of dynamic property WP_Term::$category_count is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 379

Deprecated: Creation of dynamic property WP_Term::$category_description is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 380

Deprecated: Creation of dynamic property WP_Term::$cat_name is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 381

Deprecated: Creation of dynamic property WP_Term::$category_nicename is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 382

Deprecated: Creation of dynamic property WP_Term::$category_parent is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 383

Deprecated: Creation of dynamic property WP_Term::$cat_ID is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 378

Deprecated: Creation of dynamic property WP_Term::$category_count is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 379

Deprecated: Creation of dynamic property WP_Term::$category_description is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 380

Deprecated: Creation of dynamic property WP_Term::$cat_name is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 381

Deprecated: Creation of dynamic property WP_Term::$category_nicename is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 382

Deprecated: Creation of dynamic property WP_Term::$category_parent is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 383

Deprecated: Creation of dynamic property WP_Term::$cat_ID is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 378

Deprecated: Creation of dynamic property WP_Term::$category_count is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 379

Deprecated: Creation of dynamic property WP_Term::$category_description is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 380

Deprecated: Creation of dynamic property WP_Term::$cat_name is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 381

Deprecated: Creation of dynamic property WP_Term::$category_nicename is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 382

Deprecated: Creation of dynamic property WP_Term::$category_parent is deprecated in /var/www/twodee/blog/wp-includes/category.php on line 383
cs3, fall-2021, lectures.

Dear students:

Today we begin our application of complexity analysis to real live data structures that software developers use everyday. The first data structure to go under the microscope is the array-based list. Before that, though, we need to discuss one alternative view of the complexity classes.

Limit Definitions

Last week we looked at ways of proving that growth functions were $O$, $\Omega$, or $\Theta$ of some representive growth function by finding constants that bound the growth function above and below. Sometimes finding constants is tedious work. On such occasions, you might prefer to calculate this ratio:

$$\lim_{n \rightarrow \infty} \frac{T(n)}{f(n)} = c$$

If the limit converges, then the value $c$ tells us what set the growth function belongs to:

$$\begin{array}{ll}T(n) \in \Theta(f(n)) & \text{if } 0 < c < \infty \\T(n) \in O(f(n)) & \text{if } c < \infty \\T(n) \in \Omega(f(n)) & \text{if } c > 0 \\\end{array}$$

We’re not going to prove this. Sorry.

Let’s apply this strategy in a few examples. Consider $T(n) = n^3 + 2n$ and $f(n) = n^3$. We solve the limit:

$$\begin{align}c &= \lim_{n \rightarrow \infty} \frac{n^3 + 2n}{n^3} \\ &= \lim_{n \rightarrow \infty} \left( \frac{n^3}{n^3} + \frac{2n}{n^3} \right) \\ &= \lim_{n \rightarrow \infty} \left( 1 + \frac{2}{n^2} \right) \\ &= \lim_{n \rightarrow \infty} 1 + \lim_{n \rightarrow \infty} \frac{2}{n^2} \\ &= 1 + 0 \\ &= 1\end{align}$$

Since $c = 1$, we have $\Theta$ membership.

Consider $T(n) = \frac{n}{2}$ and $f(n) = n^2$. We solve the limit:

$$\begin{align}c &= \lim_{n \rightarrow \infty} \frac{\frac{n}{2}}{n^2} \\ &= \lim_{n \rightarrow \infty} \frac{n}{2} \cdot \frac{1}{n^2} \\ &= \lim_{n \rightarrow \infty} \frac{1}{2n} \\ &= 0 \\\end{align}$$

Since $c = 0$, we have $O$ membership, but not the others.

Consider $T(n) = 2^n$ and $f(n) = 3^n$. We solve the limit:

$$\begin{align}c &= \lim_{n \rightarrow \infty} \frac{2^n}{3^n} \\ &= \lim_{n \rightarrow \infty} \left(\frac{2}{3}\right)^n \\ &= 0 \\\end{align}$$

Since $c = 0$, we have $O$ membership, but not the others.

We’ll work through $T(n) = 6n + \sqrt{n}$ and $f(n) = 2n$ as a peer instruction exercise.

ArrayList

We now move on to a discussion of data structures. For the rest of the semester we will be dragging various data structures onto the stage and discussing their complexity. Our first subject is an array-based list.

Your book introduces its own flavor of an array-based list called AList. What is the output of this program?

List<Integer> numbers = new AList<>();

for (int i = 0; i < 10000; i++) {
  numbers.append(i);
}

System.out.println(numbers.length());

It prints 10. That’s because the book has a made a design decision that makes it very different from Java’s ArrayList. The AList is a list of fixed size. The fixed size defaults to 10.

What’s the complexity of AList.append?

// Append "it" to list
public boolean append(E it) {
  if (listSize >= maxSize) {
    return false;
  }
  listArray[listSize++] = it;
  return true;
}

There’s no loop here nor any calls to expensive operations. This is a constant-time algorithm.

What is the output of this program?

List<Integer> numbers = new ArrayList<>();

for (int i = 0; i < 10000; i++) {
  numbers.add(i);
}

System.out.println(numbers.size());

This code prints 10000, as you’d expect. Java’s ArrayList does not have a fixed size. How does it manage this? It starts off with a small array of a certain length. OpenJDK starts off with 10. There aren’t any items in this array initially, so the list itself has size 0, even though the array has length 10. To track the size of the list, the ArrayList holds an extra int.

As the client calls add, the array fills up. Eventually the size of the list matches its capacity. If the client calls add on a full list, a new and bigger array is created, and all of the elements from the previous array are copied over to it. Here’s how I might implement the add method:

public void add(T item) {
  if (size >= items.length) {
    grow();
  }
  items[size] = item;
  ++size;
}

private void grow() {
  E[] biggerItems = (E[]) new Object[items.length * 2];
  for (int i = 0; i < size; ++i) {
    biggerItems[i] = items[i];
  }
  items = biggerItems;
}

This add method is different from AList.add. What can we say about it’s complexity? The cost depends on how many items have already been added to the list, so we have to look at more than just the parameter item. When the list is full, we will have to copy over all elements of the list to a new array. The worst case is therefore $\Theta(n)$. However, if the list is not full, the algorithm is constant time. The best case is therefore $\Theta(1)$.

This split leads to an interesting problem. How do we analyze this algorithm?

public static void addNumbers(int n) {
  ArrayList<Integer> nums = new ArrayList<>();

  for (int i = 0; i < n; i++) {
    nums.add(i); // Best case Theta(1), worst case Theta(n)
  }
}

The client doesn’t exactly know that this expansion is happening. However, when I time and plot these calls to add, I see a distinct pattern:

So, is the algorithm above $\Theta(n^2)$? $\Theta(n)$? Or something else?

Amortization

Suppose you ask me what I pay in property taxes each month. What do I answer? This month I didn’t pay anything. Nor will I in October. Come November, however, I’ll be shelling out $1200. In the best case, I pay $0. In the worst case, I pay $1200. In most of our analysis work so far, we’ve favored being pessimistic. However, if I say that I pay $1200 a month in property taxes, that’s overly pessimistic. It’s a misleading exaggeration.

If we know that the worst case is not so frequent, then we should perform a more nuanced analysis. A reasonable solution is to add up what I pay each month of the year and divide by 12 to get an average. This kind of reasoning is called amortized analysis. To amortize is to spread out a cost.

We should use amortized analysis to measure ArrayList.add. Calling it $\Theta(n^2)$ is a borderline lie. To ease the analysis, let’s assume that the array starts off with a single element and doubles in size once it fills. To structure our thinking, we’ll complete this table:

n assignment cost resize cost total cost amortized cost
1 1 0 1 1
2 1 1 3 1.5
3 1 2 6 2
4 1 0 7 1.75
5 1 4 12 2.4
6 1 0 13 2.167
7 1 0 14 2
8 1 0 15 1.875
9 1 8 24 2.667
… … … … …

The cost of adding element $n$ is the cost of adding all the preceding elements, plus the assignment, plus any resizing that needs to be done. Dividing the total cost by the number of times add has been called gives us the amortized cost of each add.

In general, element $n$ will have these costs:

$$\begin{align}\textrm{assignment cost} &= n \\\textrm{resize cost} &= \sum_{i=0}^{\lceil \log_2 n \rceil-1} 2^i \\\textrm{total cost} &= n + \sum_{i=0}^{\lceil \log_2 n \rceil-1} 2^i – 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{align}$$

When we average this out, we see that each add has a constant cost of around 3 operations. Thus we say that adding to an ArrayList is $\Theta(1)$, that it has amortized constant time. That’s pretty good. In fact, it’s just as good as AList, which used a fixed-size array. Even the ArrayList documentation proudly declares this.

TODO

See you next time.

Sincerely,

P.S. It’s time for a haiku!

That meal filled me up
Time to find a new body
I know, it sounds growth