Array Doubling in Data Structure


Sometimes we create array using dynamic memory allocation. If the array is allocated using dynamic memory allocation technique, we can double the size of array by performing some operations.

Suppose initial array size was 5.

Array

0
1
2
3
4
Element 1
Element 2
Element 3
Element 4
Element 5

After array doubling, the size is −

0
1
2
3
4
5
6
7
8
9
Element 1
Element 2
Element 3
Element 4
Element 5
Element 6
Element 7
Element 8
Element 9
Element 10

To double the size of array arr of size n, arr[0…n-1]. At first we have to create one new array of size say m. Then copy n elements from arr to the new array. Finally change the value of arr to point to the new array.

To create an array of size m, this will take θ(m) amount of time. This is because it will be initialized with some default values. Then it will need additional θ(n) time to copy from old array to the new array. So the operation takes θ(m + n) amount of time. This operation is taking place when the array is full. And usually the m value is same as 2n. So the complexity is θ(2n + n) = θ(3n) equivalent to θ(n). But this operation is considered as expensive. However this operation is amortized over subsequence n iterations, then it only add θ(1) time per iteration. So we can understand that array size increasing in constant factor does not adversely affect the asymptotic complexity.

Updated on: 10-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements