2.8Applications of Arrays: Strengths and Limits
Covers IGNOU MCS-208 §2.6
Arrays are the default container in most programs, but they are not always the best one. This page sums up what arrays do well and badly, with the cost of each operation, so you can judge when another structure (such as the linked lists of Unit 3) is better.
Cost of the basic operations
For an array of elements:
| Operation | Time | Why |
|---|---|---|
Read or write a[i] | Address = start + × size | |
| Search in an unsorted array | May have to check every element | |
| Search in a sorted array | Binary search (Unit 1) | |
| Insert at position | Elements move one place right | |
| Delete at position | Elements move one place left | |
| Insert or delete at the end | Nothing moves (if there is room) | |
| Change the size | Not possible | A C array has a fixed size; you must allocate a new one and copy |
Advantages and disadvantages
| Advantages | Disadvantages |
|---|---|
| access to any element by index | Fixed size: chosen in advance, too small or wasted |
| Simple to declare, traverse, search and sort | Insertion and deletion in the middle cost |
| No extra memory per element (no links) | Needs one contiguous block of memory |
| Neighbouring elements are close in memory, which suits the cache | All elements must have the same type |
Where arrays are used
Arrays are the right choice when the number of items is known in advance (or changes rarely), and when insertions and deletions in the middle are rare. Typical uses:
- tables and matrices (marks of a class, images as grids of pixels, sparse-matrix triples);
- lookup tables: precomputed answers reached by index, e.g. the prefix sums of Unit 1;
- the storage inside other data structures: stacks, queues, heaps and hash tables are often built on arrays (Units 4, 5, 9 and 10);
- strings and buffers for input and output.
Key takeaways
- Access by index is ; search is , or if the array is sorted.
- Insert and delete in the middle are because elements shift.
- Arrays suit fixed-size data with few insertions and deletions.
- Many other structures (stacks, queues, heaps, hash tables) are built on arrays.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
List three advantages and three disadvantages of arrays, and give the time complexity of access, insertion and deletion.
Show worked answer
Advantages: (1) any element is reached in by its index; (2) arrays are simple to declare, traverse, search and sort; (3) no extra memory is needed for links, and neighbouring elements are close in memory. Disadvantages: (1) the size is fixed in advance, so memory is wasted or runs out; (2) inserting or deleting in the middle needs shifting, ; (3) all elements must have the same type and the array needs one contiguous block. Complexity: access ; insertion and deletion in the worst case ( at the end).