2.2.2 Resizing

The ADT of an array should not be constrained by a capacity limited at creation time. This feature is well supported by many scripting languages, such as Perl and PHP. In other words, after an array is created, a program can refer to any element in it. Some implementations makes sure all elements in an array has default values, while others just ensures there is storage for elements.

Regardless of whether elements have default values, the difficulty is the reallocation of memory. In C, we can use the subroutine malloc to request memory. When an array increases in size, we allocate for a new and bigger array, copy everything from the existing array, then free the existing array.

This also means that resizing is an expensive operation. It is expensive because of all the data copying. An even more important impact of frequent resizing is memory fragmentation. Memory fragmentation occurs when memory chunks of different sizes are allocated and deallocated frequently.

One approach to resize an array is to always double the capacity when needed. Some approaches also shrinks the capacity of an array by half when it is okay to do so. The following is a sample verbal log of how an array adjusts its capacity:

Besides doubling/halfing, there are other techniques to change the capacity of an array. Such techniques include the use of linked lists, trees and maps. However, these techniques are quite advanced compared to the intended level of skills for this module.

Copyright © 2006-09-13 by Tak Auyeung