An unsorted array stores elements without maintaining a defined sorted order. Its occupied entries form a left-justified prefix, while a separate size value marks the boundary between data and unused storage. section 2.10 section 5.15
A class can bundle the underlying array, its capacity, and its current size. This prevents callers from having to update a separate size variable whenever they insert or delete an entry. section 2.10 section 5.15
Typical operations follow directly from the absence of ordering:
- Insert the new entry after the current last entry, then increment the size; report failure when fixed storage is full. section 2.11
- Search by scanning entries because their order provides no shortcut. section 12.5 section 10.6
- Delete an entry by finding it first; dynamic versions shift later entries left to fill the hole. section 2.17 section 5.15
- Use it when quick insertion matters more than fast searching, especially when duplicate checking is unnecessary. section 12.5
A baseball-card binder
Imagine a binder with limited capacity. Add cards in whatever order they arrive, search the whole binder to find a card to remove, and traverse the entries to print details such as a player's name and age. section 2.17
class UnsortedArray:
def __init__(self, max_size, typecode = 'l'):
self._array = Array(max_size, typecode)
self._max_size = max_size
self._size = 0
A compact constructor shows the essential representation: an internal array, maximum capacity, and zero occupied entries. section 2.10
def insert(self, new_entry):
if self._size >= len(self._array):
raise ValueError('The array is already full')
else:
self._array[self._size] = new_entry
self._size += 1
The insertion method checks capacity, writes at the occupied-prefix boundary, and increments the stored size. section 2.11
