# Arrays & Dynamic Arrays

In depth explanation of dynamic arrays.

May 25, 2020

## Transcript

1. 1.

overview
2. 2.

### Collection of values of the same type, stored in contiguous

memory, accessible by an index.
3. 3.

### Collection of values of the same type, stored in contiguous

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

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

boolean values. • Have a clear internal binary representation.
5. 5.

6. 6.

size 4:
7. 7.

### Storing integers int = 4 bytes (C/C++) int arr =

{255, -10, 13, 0, 40, -8};
8. 8.

### Storing integers int = 4 bytes (C/C++) int arr =

{255, -10, 13, 0, 40, -8};
9. 9.

10. 10.

### Indexes int arr = {255, -10, 13, 0, 40, -8};

arr arr arr arr arr arr
11. 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
12. 12.

### arr 0xA100 S = bytes t = 4 N =

6 int arr = {255, -10, 13, 0, 40, -8}; arr arr arr arr 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 0xA100 + 16 = 0xA110 = S + (t ⋅ 4) =
13. 13.

0, 40, -8};
14. 14.

### Operations • Lookup • Time complexity: • Modiﬁcation • 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)
15. 15.

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)
16. 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 ﬁnd all occurrences of x ﬁrst. • Time complexity: O(n) O(n2)
17. 17.

18. 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
19. 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)
20. 20.

21. 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
22. 22.