Sub topic 3
Array Operations: Access, Search, Insert, and Delete
Assume you know loops, indexing, references, and introductory Big-O notation. This chapter uses a zero-based array, so the first element is at index 0.
The cost model
An array stores elements in contiguous memory. Because every element has the same size, the address of element i can be calculated directly:
\[ \text{address}(A[i]) = \text{base address} + i \times \text{element size} \]
This makes indexed access constant time, written as O(1). The operation does not become slower when the array grows.
| Operation | Typical cost | Reason |
|---|---|---|
| Access `A[i]` | O(1) | Calculate the address directly |
| Search unsorted array | O(n) | May inspect every element |
| Search sorted array | O(log n) | Binary search can discard half the range |
| Insert at end | O(1) amortized | Space may already be available |
| Insert at beginning or middle | O(n) | Elements must shift |
| Delete at beginning or middle | O(n) | Elements must shift |
“Amortized” means the average cost over many operations. In a resizable array, an occasional resize takes O(n), but most append operations take O(1).
Access and search
Access is direct:
values = [12, 7, 25, 4]
print(values[2]) # 25A linear search checks elements from left to right:
def linear_search(values, target):
for i, value in enumerate(values):
if value == target:
return i
return -1
print(linear_search([12, 7, 25, 4], 25)) # 2The worst case occurs when the target is absent or is the last element. Therefore, the running time is O(n). Do not use binary search unless the array is sorted and the search maintains valid lower and upper bounds.
Insertion and deletion
Inserting at index i requires shifting elements from the right side one position right. Deleting at index i shifts later elements left.
def insert_at(values, index, item):
values.append(None)
for j in range(len(values) - 1, index, -1):
values[j] = values[j - 1]
values[index] = item
def delete_at(values, index):
removed = values[index]
for j in range(index, len(values) - 1):
values[j] = values[j + 1]
values.pop()
return removed
data = [10, 20, 40]
insert_at(data, 2, 30)
print(data) # [10, 20, 30, 40]
print(delete_at(data, 1)) # 20
print(data) # [10, 30, 40]The loop direction matters. During insertion, shift right from the end so values are not overwritten. During deletion, shift left from the deleted position.
Exercise
An array has n elements. What is the worst-case cost of inserting a new element at index 0, and why?
Show answer
O(n), because every existing element must shift one position to the right.