Arrays

Table of Contents

Arrays

int arr[6] = {10,20,30,40,50,60};

Visually a memory allocated array looks like this.

Array.png

As a list, it might look like this: ArrayList.png

Complexity

Worst Case Array List


Space O(n) O(n) Traversal O(n) O(n) Lookup O(1) O(n) Append O(1) O(n) Prepend O(n) O(1) Insert O(n) O(n) Delete O(n) O(n)

Resizing

struct Array {
  int* items;
  size_t length;
  size_t capacity;
}
void append(struct Array arr, int value) {
  if (arr.length == arr.capacity) {
    // resize array
    int* new_arr = malloc(sizeof(int) * capacity * 2);
    for (int i = 0; i < arr.length; i++) {
      new_arr[i] = arr[i];
    }
    free(arr->items);
    arr->items = new_arr;
    arr->items[length] = value;
    arr.length++;
    arr.capacity *= 2;
  } else {
    // don't resize array.
    arr.items[length] = value;
    arr.length++;
  }
}