2.2Dynamic Arrays
What is a dynamic array?
An ordinary array gets its size when it is created and keeps it. Yet most programs do not know in advance how many elements will arrive. A dynamic array solves this by moving itself into a larger array when it fills up. The Python list you use every day works this way.
- The difference between size and capacity, and what happens when the array is full
- How dynamic arrays are used in Python, Java, C++ and C
- Why the capacity doubles instead of growing by one
1The problem with a fixed array
When you write int arr[8]; in C, room for 8 elements is set aside and there is no room for a ninth. Allocate too little and you run out; allocate too much and memory goes to waste. If the amount of data is only known while the program runs, both are bad.
A dynamic array solves this as follows: inside, it still keeps an ordinary array, but when that array is full it allocates a larger one, moves the elements across and releases the old one. From the outside, the array seems to have grown on its own.
2Size and capacity
A dynamic array keeps two numbers. The size is the number of elements actually stored. The capacity is the number of slots allocated for the inner array. The size is always less than or equal to the capacity.
While the size is less than the capacity, a new element goes straight into arr[size] and the size grows by one. This is the same as appending to a fixed array and takes O(1).
3When the array is full
If a new element arrives while the size equals the capacity, the array grows:
- A new, larger array is allocated, usually with twice the capacity.
- The old elements are copied into it at the same indices.
- The old array is released (in C with free).
- The new element is written into
arr[size], which is now free.
Copying takes size steps, so it is O(n). But it only happens when the array is full. The code for these steps is in Growing the capacity.
4Dynamic arrays in different languages
Most languages ship a dynamic array, and you never see it grow:
| Language | Dynamic array | Append |
|---|---|---|
| Python | list | items.append(x) |
| Java | ArrayList<Integer> | items.add(x) |
| C++ | std::vector<int> | v.push_back(x) |
| C | None; written by hand with malloc and realloc | Your own function |
numbers = [] # an empty listfor i in range(10): numbers.append(i) # grows by itself when fullprint(len(numbers)) # 10ArrayList<Integer> numbers = new ArrayList<>();for (int i = 0; i < 10; i++) numbers.add(i); // grows by itself when fullSystem.out.println(numbers.size()); // 10C has no built-in dynamic array. You allocate the array with malloc and grow it with realloc when it is full. realloc tries to grow the block in place; if there is no room, it allocates a new block, copies the elements and releases the old one.
int capacity = 4, size = 0;int* arr = malloc(capacity * sizeof(int)); // when appending a new element:if (size == capacity) { int* bigger = realloc(arr, 2 * capacity * sizeof(int)); if (bigger == NULL) return; // no memory, the array is unchanged arr = bigger; capacity *= 2;}arr[size++] = value;The growth factor depends on the language. Java's ArrayList grows its capacity by about 1.5 times, C++ libraries mostly use 1.5 or 2, and the Python list sets aside about one eighth more room each time. What they share is that the growth is proportional to the size, not a fixed number.
5Why double, and not add one?
The first idea is to add one slot when the array is full. But then the array is full again at every append, and every append copies all the elements. Appending the 1000th element moves 999 elements.
Starting from capacity 1, the number of copies needed to append the elements is:
| Growth rule | 1,000 elements | 1,000,000 elements |
|---|---|---|
| Add 1 each time | 499,500 copies | about 500 billion copies |
| Double each time | 1,023 copies | 1,048,575 copies |
Adding one gives 1 + 2 + ... + (n - 1) copies, which is O(n²). Doubling gives 1 + 2 + 4 + ... copies, and that sum never exceeds 2n. The total for n appends is O(n); spread over all appends, each element gets a constant share.
This is called amortized O(1): most single appends are O(1) and now and then one takes O(n), but the average over a long run of appends is constant. The price is memory: right after growing, half of the array is empty.
In short: appending to a dynamic array is amortized O(1) and O(n) in the worst case. Access by index is always O(1), just as in an ordinary array.
6Try it
A dynamic array has capacity 8 and size 5. What happens if you append 3 elements?
The answer is B. There are three free slots and the three elements go straight into them. The array only grows if a ninth element arrives while the size is 8.
Show the answer
The answer is B. There are three free slots and the three elements go straight into them. The array only grows if a ninth element arrives while the size is 8.
Why is it slow to append 1000 elements to a dynamic array that grows its capacity by only 1 each time it is full?
The answer is A. The capacity always equals the size, so every append means a growth and a full copy. The total is 1 + 2 + ... + 999 = 499,500 copies, which is O(n²).
Show the answer
The answer is A. The capacity always equals the size, so every append means a growth and a full copy. The total is 1 + 2 + ... + 999 = 499,500 copies, which is O(n²).
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.