Arrays & Dynamic Arrays

Arrays & Dynamic Arrays

In depth explanation of dynamic arrays.

3fafd51aa8dad766208e11eaaa1d534c?s=128

Pablo Ángel Trinidad

May 25, 2020
Tweet

Transcript

  1. 3.

    Collection of values of the same type, stored in contiguous

    memory, accessible by an index. •Same type? •Contiguous memory? •Index?
  2. 4.

    Primitive data types • Represent “elemental” data like numbers and

    boolean values. • Have a clear internal binary representation.
  3. 10.

    Indexes int arr[6] = {255, -10, 13, 0, 40, -8};

    arr[0] arr[1] arr[2] arr[3] arr[4] arr[5]
  4. 11.

    If is the address of an array, is the size

    of one of its elements and the number of elements: S t N • The total size of the array is: • The i-th element can be located at address • The array ends at memory address N ⋅ t A[i] = S + ti S + Ni
  5. 12.

    arr[0] 0xA100 S = bytes t = 4 N =

    6 int arr[6] = {255, -10, 13, 0, 40, -8}; arr[1] arr[2] arr[5] arr[3] 0xA100 + 0 = 0xA100 = S + (t ⋅ 0) = 0xA100 + 4 = 0xA104 = S + (t ⋅ 1) = 0xA100 + 8 = 0xA108 = S + (t ⋅ 2) = 0xA100 + 12 = 0xA10C = S + (t ⋅ 3) = 0xA100 + 20 = 0xA114 = S + (t ⋅ 5) = arr[4] 0xA100 + 16 = 0xA110 = S + (t ⋅ 4) =
  6. 14.

    Operations • Lookup • Time complexity: • Modification • Time

    complexity: A[i] O(1) A[i] = x O(1) NOT SUPPORTED • Insertion: • A.push(x) • A.insert(x, i) • Deletion: • A.remove(x) • A.delete(i)
  7. 15.

    Insertion Complications • A.push(x) requires to add additional space at

    the end of the array which cannot be guaranteed to be available • Solution: Allocate new memory of size , move every element to the new location, and add the new element. • Time/space complexity: • A.insert(x, i) is the same as push(x) but shifts all elements after i 1 place to the right • Time/space complexity: N + 1 Θ(n) Θ(n)
  8. 16.

    Deletion Complications • A.delete(i) must move all elements to the

    right of i 1 place to the left. • Time complexity: • A.remove(x) is the same as delete(i) but it has to find all occurrences of x first. • Time complexity: O(n) O(n2)
  9. 18.

    Dynamic arrays How they work • Initialize array with additional

    space • Keep track of the last element/length • Whenever an insertion surpasses the underlying array capacity: • Allocate new memory of size where • Copy all elements of the original array to the new location • Add new element ρN ρ > 1
  10. 19.

    Dynamic arrays How they work Time complexity Operation Worst case

    Amortized Add at end Delete at end Add/delete at beginning Get Set O(n) O(n) O(n) O(1) O(1) O(1) O(1) O(1) O(1) O(1)
  11. 21.

    Dynamic arrays Implementations • Java: java.util.ArrayList • Python: built-in list

    • Javascript: built-in array • Golang: built-in slice • C++: std::vector • Ruby: built-in Array