algoritmauzmanı
Sign in
TREN
2.2Dynamic Arrays
Lesson 2.2.1

What is a dynamic array?

An ordinary gets its size when it is created and keeps it. Yet most programs do not know in advance how many elements will arrive. A solves this by moving itself into a larger array when it fills up. The Python list you use every day works this way.

What you will learn
  • 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
5 min

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.

in use: size = 5free12071329354567
Capacity 8, size 5. The first five slots are in use; the last three are allocated but empty. The next element goes to index 5.

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 .

3When the array is full

If a new element arrives while the size equals the capacity, the array grows:

  1. A new, larger array is allocated, usually with twice the capacity.
  2. The old elements are copied into it at the same indices.
  3. The old array is released (in C with ).
  4. The new element is written into arr[size], which is now free.
old array: capacity 4, fullnew array: capacity 812071329312071329354567
Appending 5 to a full array with capacity 4. The four elements were copied into a new array of 8 slots, and 5 went into a free slot. The old array is about to be released.

Copying takes size steps, so it is . 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:

LanguageDynamic arrayAppend
Pythonlistitems.append(x)
JavaArrayList<Integer>items.add(x)
C++std::vector<int>v.push_back(x)
CNone; written by hand with malloc and reallocYour own function
numbers = []            # an empty listfor i in range(10):    numbers.append(i)   # grows by itself when fullprint(len(numbers))     # 10
ArrayList<Integer> numbers = new ArrayList<>();for (int i = 0; i < 10; i++)    numbers.add(i);     // grows by itself when fullSystem.out.println(numbers.size());  // 10

C has no built-in dynamic array. You allocate the array with 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 rule1,000 elements1,000,000 elements
Add 1 each time499,500 copiesabout 500 billion copies
Double each time1,023 copies1,048,575 copies

Adding one gives 1 + 2 + ... + (n - 1) copies, which is . 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 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?

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?

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 .

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.