An array is simply a list of items. Every item is next to each other in memory.
4
1
24
8
9
This means accessing an item is very fast, but inserting or deleting an item is slow because all the items after it have to be moved.
We want to access the 3rd item in the array, which is at index 2.
4
1
24
8
9
We have an array :
4
1
24
8
9
We want to insert the value 10 at index 2.
We allocate a new array of size 6 (5 + 1)
We copy the first 2 elements from the old array to the new array.
4
1
We insert the new value at index 2.
4
1
10
We copy the remaining elements from the old array to the new array.
4
1
10
24
8
9
We have an array :
4
1
24
8
9
We want to remove the value at index 2.
We allocate a new array of size 4 (5 - 1)
We copy the first 2 elements from the old array to the new array.
4
1
We copy the last 2 elements from the old array to the new array.
4
1
8
9