Linear search
To find one lantern’s record, the simplest plan is to look at each record in turn. A linear search checks the records one at a time from index 0. It stops when it finds the search key or runs out of records. The records need no initial ordering.
Tavren lantern hire keeps six lantern records as [ID, watts]. The search key is an ID.
Each column is one record. Read the IDs from index 0: every amber one is compared and rejected, until 22 matches.
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| ID items[pos][0] | 31 | 14 | 27 | 8 | 22 | 19 |
| watts items[pos][1] | 6 | 9 | 12 | 6 | 12 | 9 |
| ID | Watts |
|---|---|
| 31 | 6 |
| 14 | 9 |
| 27 | 12 |
| 8 | 6 |
| 22 | 12 |
| 19 | 9 |
1def linear(items, target): 2for pos in range(len(items)): 3if items[pos][0] == target: 4return pos 5return -1
Trace the search to its result
Four passes fail the test on line 3. Watch the one that succeeds, then check it against the whole run.
| Line | Statement that runs | pos | Returns | Writes | What happens |
|---|---|---|---|---|---|
| 2 | for pos in range(len(items)): | 4 | pos 4 | the next index | |
| the next index | |||||
| 3 | if items[pos][0] == target: | test items[4][0] is 22: 22 = 22 is true | |||
| test items[4][0] is 22: 22 = 22 is true | |||||
| 4 | return pos | 4 | Returns 4 | the search stops; the caller gets index 4 | |
| the search stops; the caller gets index 4 | |||||
pos | items[pos][0] | Returns | What happens | |
|---|---|---|---|---|
| pass 1 | 0 | 31 | 31 ≠ 22: try the next index | |
| 31 ≠ 22: try the next index | ||||
| pass 2 | 1 | 14 | 14 ≠ 22: try the next index | |
| 14 ≠ 22: try the next index | ||||
| pass 3 | 2 | 27 | 27 ≠ 22: try the next index | |
| 27 ≠ 22: try the next index | ||||
| pass 4 | 3 | 8 | 8 ≠ 22: try the next index | |
| 8 ≠ 22: try the next index | ||||
| pass 5 | 4 | 22 | 4 | 22 = 22: return 4 |
| 22 = 22: return 4 | ||||
| Target | IDs compared | Result |
|---|---|---|
| 22 | 31, 14, 27, 8, 22 | 4: record [22, 12] |
| 25 | all six IDs | −1: absent |
- For an absent key such as 25, all six IDs are compared, the loop ends and line 5 returns −1.
- Indexes are 0 to 5, so −1 can never be mistaken for a found record.
- Test for −1 before using the result: in Python,
items[-1]would read the last record.
1 Which IDs are compared when the target is 8, and what is returned?
2 How many IDs are compared when the target is 19?
3 The target is 40. What is returned, and what would items[result] read in Python if the program did not test it first?
- 131, 14, 27, 8; returns 3
- 2all 6; it returns 5
- 3−1 after comparing all 6;
items[-1]is the last record, [19, 9], which is not ID 40
Bubble sort
Sorted records can be searched far faster, so putting them in order is often worth the effort. Bubble sort compares each pair of neighbours and swaps them if they are out of order. After each pass the largest remaining ID has moved to the end.
Sort Tavren’s [ID, watts] records, [31, 6], [14, 9], [27, 12], [8, 6], [22, 12], [19, 9], ascending by ID. Each cell drawn below is a whole record; only its ID is shown.
1def bubble(items): 2end = len(items) - 1 3swapped = True 4while end > 0 and swapped: 5swapped = False 6for j in range(end): 7if items[j][0] > items[j + 1][0]: 8temp = items[j] 9items[j] = items[j + 1] 10items[j + 1] = temp 11swapped = True 12end = end - 1
Follow 31 through pass 1. Each blue pair is compared, and the larger ID is swapped one place towards the end.
| Line | Statement that runs | temp | items[j] | items[j + 1] | swapped | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 7 | if items[j][0] > items[j + 1][0]: | test 31 > 14 is true: swap | |||||
| test 31 > 14 is true: swap | |||||||
| 8 | temp = items[j] | [31, 6] | temp [31, 6] | save the left record | |||
| save the left record | |||||||
| 9 | items[j] = items[j + 1] | [14, 9] | items[j] [14, 9] | copy the right record left | |||
| copy the right record left | |||||||
| 10 | items[j + 1] = temp | [31, 6] | items[j + 1] [31, 6] | the saved record goes right | |||
| the saved record goes right | |||||||
| 11 | swapped = True | True | swapped True | a swap happened in this pass | |||
| a swap happened in this pass | |||||||
The whole sort: one row per pass
Each row is one pass of the while loop. Watch end shrink by 1, and swapped decide when the sort can stop.
end | Compares | Swaps | swapped | IDs after the pass | What it settled | |
|---|---|---|---|---|---|---|
| start | 5 | True | 31 14 27 8 22 19 | lines 2 and 3 | ||
| lines 2 and 3 | ||||||
| pass 1 | 4 | 5 | 5 | True | 14 27 8 22 19 31 | 31 is now in place at index 5 |
| 31 is now in place at index 5 | ||||||
| pass 2 | 3 | 4 | 3 | True | 14 8 22 19 27 31 | 27 is now in place at index 4 |
| 27 is now in place at index 4 | ||||||
| pass 3 | 2 | 3 | 2 | True | 8 14 19 22 27 31 | 22 is now in place at index 3 |
| 22 is now in place at index 3 | ||||||
| pass 4 | 1 | 2 | 0 | False | 8 14 19 22 27 31 | no swaps: swapped stays False, so the loop stops |
| no swaps: swapped stays False, so the loop stops | ||||||
| Pass | Comparisons | Swaps | IDs after pass |
|---|---|---|---|
| 1 | 5 | 5 | 14 27 8 22 19 31 |
| 2 | 4 | 3 | 14 8 22 19 27 31 |
| 3 | 3 | 2 | 8 14 19 22 27 31 |
| 4 | 2 | 0 | 8 14 19 22 27 31 |
How the loop controls work
Two small details stop the sort doing wasted work:
- 1
endshrinks by 1 after each pass: the last ID of that pass is already in place. - 2
swappedis reset to False at the start of each pass. A pass with no swaps proves the order is correct, so the loop stops. - 3
range(end)stops at end − 1, soj + 1stays inside the active range. - 4Swap the whole record so its wattage stays attached. Equal IDs are never swapped, so they keep their order. Changing
>to<sorts descending.
1 Records with IDs 12, 5, 9, 3 are bubble sorted by ID. Give the IDs after pass 1.
2 How many swaps happen in pass 1?
3 How many passes run in total, and what stops the loop?
- 15, 9, 3, 12
- 23
- 33: end reached 0 (the swaps per pass are 3, 1, 1)
Insertion sort
Most people sort a hand of cards by sliding each new card into place among the ones already sorted. Insertion sort builds a sorted part at the start of the array. Each pass saves the next record, shifts larger records one place right, then puts the saved record into the gap.
Start with the same [ID, watts] records [31, 6], [14, 9], [27, 12], [8, 6], [22, 12], [19, 9]. The trace sorts on field 0, the ID. Records are shifted, not swapped.
1def insertion(items, field): 2for pos in range(1, len(items)): 3saved = items[pos] 4j = pos - 1 5while (j >= 0 6and items[j][field] > saved[field]): 7items[j + 1] = items[j] 8j = j - 1 9items[j + 1] = saved 10return items
Green is the sorted part, growing by one record each pass. Find the saved record in violet and count how many IDs shift to make its gap.
| Line | Statement that runs | saved | j | items[j + 1] | Writes | What happens |
|---|---|---|---|---|---|---|
| 3 | saved = items[pos] | [22, 12] | saved [22, 12] | save the record at index 4 | ||
| save the record at index 4 | ||||||
| 4 | j = pos - 1 | 3 | j 3 | start just left of it | ||
| start just left of it | ||||||
| 5 | while (j >= 0 and items[j][field] > saved[field]): | test 31 > 22 is true | ||||
| test 31 > 22 is true | ||||||
| 7 | items[j + 1] = items[j] | [31, 6] | items[j + 1] [31, 6] | 31 shifts right to index 4 | ||
| 31 shifts right to index 4 | ||||||
| 8 | j = j - 1 | 2 | j 2 | |||
| 5 | while (j >= 0 and items[j][field] > saved[field]): | test 27 > 22 is true | ||||
| test 27 > 22 is true | ||||||
| 7 | items[j + 1] = items[j] | [27, 12] | items[j + 1] [27, 12] | 27 shifts right to index 3 | ||
| 27 shifts right to index 3 | ||||||
| 8 | j = j - 1 | 1 | j 1 | |||
| 5 | while (j >= 0 and items[j][field] > saved[field]): | test 14 > 22 is false: stop shifting | ||||
| test 14 > 22 is false: stop shifting | ||||||
| 9 | items[j + 1] = saved | [22, 12] | items[j + 1] [22, 12] | 22 goes into the gap at index 2 | ||
| 22 goes into the gap at index 2 | ||||||
The whole sort: one row per pass
One row per pass. The shifted IDs explain where each saved record lands.
saved | Shifted right | Lands at | IDs after the pass | Why | |
|---|---|---|---|---|---|
| pos 1 | 14 | 31 | 0 | 14 31 27 8 22 19 | 31 is larger than 14: shift right |
| 31 is larger than 14: shift right | |||||
| pos 2 | 27 | 31 | 1 | 14 27 31 8 22 19 | 31 is larger than 27: shift right |
| 31 is larger than 27: shift right | |||||
| pos 3 | 8 | 31, 27, 14 | 0 | 8 14 27 31 22 19 | 31, 27, 14 are larger than 8: shift right |
| 31, 27, 14 are larger than 8: shift right | |||||
| pos 4 | 22 | 31, 27 | 2 | 8 14 22 27 31 19 | 31, 27 are larger than 22: shift right |
| 31, 27 are larger than 22: shift right | |||||
| pos 5 | 19 | 31, 27, 22 | 2 | 8 14 19 22 27 31 | 31, 27, 22 are larger than 19: shift right |
| 31, 27, 22 are larger than 19: shift right | |||||
| Saved ID | Shift right | IDs after insertion |
|---|---|---|
| 14 | 31 | 14 31 27 8 22 19 |
| 27 | 31 | 14 27 31 8 22 19 |
| 8 | 31, 27, 14 | 8 14 27 31 22 19 |
| 22 | 31, 27 | 8 14 22 27 31 19 |
| 19 | 31, 27, 22 | 8 14 19 22 27 31 |
Sort on another field
A sort can order the records on any field, not only the ID:
- 1
insertion(items, 0)orders by ID;insertion(items, 1)orders by wattage. By watts the IDs become 31, 8, 14, 19, 27, 22. - 2The strict
>leaves equal watts in their arrival order. - 3Checking
j >= 0before readingitems[j]stops the loop crossing the lower bound. - 4For parallel arrays, save both ID and wattage, shift both at each index, then restore both at
j + 1.
1 Records with IDs 9, 4, 7, 2 are insertion sorted by ID. Give the IDs after the pass with pos = 1.
2 In the pass that saves 2, which IDs shift right?
3 How many shifts does the whole sort make?
- 14, 9, 7, 2
- 29, 7, 4
- 35
Binary search
Sorted IDs need not be checked one by one. Binary search needs data sorted on the key, with direct access to the middle element. It checks the middle item; if that is not the key, it discards the half that cannot contain it.
Then it repeats on the half that is left. Tavren’s records in ascending ID order: 8, 14, 19, 22, 27, 31.
1def binary(items, target): 2low = 0 3high = len(items) - 1 4while low <= high: 5mid = (low + high) // 2 6if items[mid][0] == target: 7return mid 8if items[mid][0] < target: 9low = mid + 1 10else: 11high = mid - 1 12return -1
Trace low, high and mid
Each pass tests the blue middle ID, then turns one half amber: those IDs cannot hold 22. Watch how few candidates are left after three tests.
| Line | Statement that runs | low | high | mid | Writes | What happens |
|---|---|---|---|---|---|---|
| 5 | mid = (low + high) // 2 | 2 | mid 2 | (0 + 5) // 2 = 2 | ||
| (0 + 5) // 2 = 2 | ||||||
| 6 | if items[mid][0] == target: | test items[2][0] is 19: 19 = 22 is false | ||||
| test items[2][0] is 19: 19 = 22 is false | ||||||
| 8 | if items[mid][0] < target: | test 19 < 22 is true: 22 must be to the right | ||||
| test 19 < 22 is true: 22 must be to the right | ||||||
| 9 | low = mid + 1 | 3 | low 3 | indexes 0 to 2 are discarded | ||
| indexes 0 to 2 are discarded | ||||||
low | high | mid | items[mid][0] | What happens | |
|---|---|---|---|---|---|
| start | 0 | 5 | lines 2 and 3: every index is a candidate | ||
| lines 2 and 3: every index is a candidate | |||||
| pass 1 | 3 | 2 | 19 | 19 < 22: low = mid + 1 | |
| 19 < 22: low = mid + 1 | |||||
| pass 2 | 3 | 4 | 27 | 27 > 22: high = mid − 1 | |
| 27 > 22: high = mid − 1 | |||||
| pass 3 | 3 | 22 | 22 = 22: return 3 | ||
| 22 = 22: return 3 | |||||
The key 25 is absent: the same three tests, then the bounds cross.
low | high | mid | items[mid][0] | What happens | |
|---|---|---|---|---|---|
| start | 0 | 5 | lines 2 and 3: every index is a candidate | ||
| lines 2 and 3: every index is a candidate | |||||
| pass 1 | 3 | 2 | 19 | 19 < 25: low = mid + 1 | |
| 19 < 25: low = mid + 1 | |||||
| pass 2 | 3 | 4 | 27 | 27 > 25: high = mid − 1 | |
| 27 > 25: high = mid − 1 | |||||
| pass 3 | 4 | 3 | 22 | 22 < 25: low = mid + 1 | |
| 22 < 25: low = mid + 1 | |||||
| end | low 4 > high 3: no candidate left, return −1 | ||||
| low 4 > high 3: no candidate left, return −1 | |||||
| Target | low, high | mid → ID | Next action |
|---|---|---|---|
| 22 | 0, 5 | 2 → 19 | low = 3 |
| 22 | 3, 5 | 4 → 27 | high = 3 |
| 22 | 3, 3 | 3 → 22 | return 3 |
| 25 | 0, 5 | 2 → 19 | low = 3 |
| 25 | 3, 5 | 4 → 27 | high = 3 |
| 25 | 3, 3 | 3 → 22 | low = 4: stop |
- 1The tested midpoint is excluded with mid + 1 or mid − 1. Otherwise a one-item range can repeat forever.
- 2When low > high, no candidate remains: return −1.
- 3
//is integer division, so the midpoint is always an index.
Exclude the tested midpoint with mid + 1 or mid − 1. Otherwise a one-item range can repeat forever. When low > high, no candidate remains. // is integer division; the midpoint must be an index.
1 Search for 8. Which IDs are compared, and what is returned?
2 Search for 31. Give mid for each pass.
3 Search for 10. Give low and high when the loop stops, and the value returned.
- 119, 8; returns 0
- 22, 4, 5; it returns 5
- 3low 1, high 0; returns −1
Comparing search and sort costs
With six records, every method finishes in an instant. The difference shows with thousands. Time complexity describes how an operation count grows with input size n. Space complexity describes memory growth. Big O gives an upper growth class; it does not measure seconds on a particular computer.
Learn this table: the best and worst time for each algorithm, and the extra memory it needs.
| Algorithm | Best time | Worst time | Auxiliary space |
|---|---|---|---|
| Linear search | O(1) | O(n) | O(1) |
| Binary search, iterative | O(1) | O(log n) | O(1) |
| Bubble, early exit | O(n) | O(n²) | O(1) |
| Insertion sort | O(n) | O(n²) | O(1) |
How the work grows with n
Each bar is how many IDs are still candidates before a test. Halving every time, 15 items need only 4 tests.
- A failed linear search tests all n keys. Doubling n roughly doubles that work.
- Binary search halves the range each time: at most 4, 5, 6 midpoint tests for 15, 31, 63 items. Doubling the data adds about one test.
A sort’s work depends on the order it is given, not only on n. Compare the two rows: the same items, ordered and reversed.
| Insertion input | Six items | Twelve items |
|---|---|---|
| Already ordered | 5 key comparisons | 11 key comparisons |
| Reverse order | 15 shifts | 66 shifts |
- Reverse order needs n(n − 1)/2 shifts, so the growth is quadratic.
- More items and a less ordered input mean more work. Nearly ordered input needs few shifts.
How much memory each needs
- These sorts rearrange the original array with a few temporary variables: O(1) auxiliary space.
- The records themselves still occupy O(n) storage. Copying the entire array would add O(n) auxiliary space.
- Sorting once for many searches may repay its initial cost. For one search of a small unsorted input, a scan may be better.
1 At most how many midpoint tests does binary search need for 127 items?
2 A linear search for an absent ID runs on 200 records. How many IDs are compared?
3 Insertion sort is given 8 records in reverse order. How many shifts does it make?
- 17
- 2200: every one
- 328: 8 × 7 ÷ 2
Counting and sorting strings
Tavren also records each lantern’s status as a word, and “Available” and “available” should count as the same. Search and insertion work on strings once the comparison rule is explicit: Tavren treats status names as case-insensitive, and sorts their lower-case forms alphabetically.
Three rows: the statuses as typed, their lower-case forms, then the sorted array. Only the lower-case forms are compared with the target.
def count_status(items, target): target = target.lower() total = 0 for item in items: if item.lower() == target: total = total + 1 return total
- To count every occurrence, carry on after a match instead of returning its first index.
- Normalise both the stored values and the target; otherwise differently capitalised forms may be missed.
Sort the strings and keep the result
insertion_text hands back the array it sorted. The main program stores that result, then prints it.
def insertion_text(items): for pos in range(1, len(items)): saved = items[pos] j = pos - 1 while j >= 0 and items[j] > saved: items[j + 1] = items[j] j = j - 1 items[j + 1] = saved return items
statuses = ["Repair", "AVAILABLE", "On-loan", "available"] statuses = [value.lower() for value in statuses] print("Matches", count_status(statuses, "Available")) print("Before", statuses) ordered = insertion_text(statuses) print("After", ordered)
Observed output: Matches 2; Before: repair, available, on-loan, available; After: available, available, on-loan, repair.
The driver stores and outputs the returned array. Both functions work for any array length, including zero.
1 The array holds Repair, REPAIR, on-loan, Lost and the target is repair. What does count_status return?
2 If only the target were made lower case, how many of those four would match?
3 insertion_text is given repair, lost, available. What array does it return?
- 12
- 20: “Repair” and “REPAIR” no longer equal “repair”
- 3['available', 'lost', 'repair']
Sorting strings by length
A sort has no idea what “in order” means; the comparison decides. Tavren orders status strings by number of characters, rather than alphabetical order. Keep the bubble-sort passes, adjacent swaps and early-exit flag.
def bubble_length(items): end = len(items) - 1 swapped = True while end > 0 and swapped: swapped = False for j in range(end): if len(items[j]) > len(items[j + 1]): temp = items[j] items[j] = items[j + 1] items[j + 1] = temp swapped = True end = end - 1
The number under each string is its length. Follow the longest string to the end, one pass at a time.
Now count the swaps. The loop stops only after a pass that makes none.
| Compares | Swaps | swapped | Strings after the pass | What it settled | |
|---|---|---|---|---|---|
| pass 1 | 3 | 3 | True | repair, on-loan, repair, available | available (9 characters) is in place |
| available (9 characters) is in place | |||||
| pass 2 | 2 | 1 | True | repair, repair, on-loan, available | on-loan (7 characters) is in place |
| on-loan (7 characters) is in place | |||||
| pass 3 | 1 | 0 | False | repair, repair, on-loan, available | no swaps: only now can the early exit stop the loop |
| no swaps: only now can the early exit stop the loop | |||||
statuses = ["available", "repair", "on-loan", "repair"] print("Before", statuses) bubble_length(statuses) print("After", statuses) for value in statuses: print(value, len(value))
| Pass | Strings after pass | Swaps |
|---|---|---|
| 1 | repair, on-loan, repair, available | 3 |
| 2 | repair, repair, on-loan, available | 1 |
| 3 | repair, repair, on-loan, available | 0 |
- Observed output lengths are 6, 6, 7, 9.
- Only the last pass makes no swaps, so only then can the early-exit flag stop the loop.
- Alphabetical order would start with available despite its greater length: that would answer a different requirement.
1 Sort available, lost, repair by length. Give the strings after pass 1.
2 How many passes run?
3 Sort repair, signal, lost by length. Which of the two 6-character strings comes first, and why?
- 1lost, repair, available
- 22
- 3repair: equal lengths are not swapped, so repair keeps its place before signal
ADT interfaces and implementations
Code that uses a stack should not care whether it is built from an array or a linked list. An abstract data type (ADT) specifies stored values and allowed operations without fixing their representation. Its interface tells a caller what an operation does; its implementation supplies arrays, records, links and code.
Four ADTs, each drawn as its shape. The line under each is the rule a caller relies on, whatever builds it.
Start from what Tavren needs. The need picks the ADT and its operations; only then choose how to build it.
| Tavren need | ADT and operations | Implementation choice |
|---|---|---|
| Most recent return checked first | Stack: push, pop, isEmpty | Array and top index |
| Requests served in arrival order | Queue: enqueue, dequeue | Circular array and pointers |
| Editable ordered route of IDs | Linked list: find, insert, delete | Node records and links |
| Find an ID by ordered branching | Binary search tree: find, insert | Left/data/right node records |
Build a stack from a linked list
- The user still sees LIFO push and pop.
- Changing from an array to linked storage changes the implementation, not that contract.
- A fixed array can fill even though the logical stack can grow and shrink.
What each operation returns on failure
Any operation can fail: a full array, an empty queue, a missing ID. Each one reports failure in its own way.
| Operation | Failure result |
|---|---|
| Insertion refused | False |
| Unsuccessful search | −1 |
| Stack pop or circular-queue dequeue when empty | None |
| Linear-queue removal when empty | −1 |
Neither None nor −1 is a valid lantern ID. Callers check the operation’s stated result before using data.
1 Requests must be served in the order they arrive. Which ADT fits?
2 The last check must be undone first. Which ADT fits?
3 A stack’s storage changes from an array to a linked list. What changes for the program that calls push and pop?
- 1a queue (first in, first out)
- 2a stack (last in, first out)
- 3nothing it can see: push and pop still behave LIFO; only the implementation changed
Linked-list storage
A linked list keeps its order in pointers, so nothing has to move to make room. A node contains data and a next pointer. An array index acts as its address. head identifies the first active node; free identifies the first unused node. The null pointer −1 is outside indexes 0–5.
At the start every cell is on the free chain. values walks any chain by following link until it reaches −1.
1NULL = -1 2data = [None] * 6 3link = [1, 2, 3, 4, 5, NULL] 4head = NULL 5free = 0 6 7def values(start, indices=False): 8result = [] 9current = start 10while current != NULL: 11result.append(current if indices 12else data[current]) 13current = link[current] 14return result
Follow the links, not the rows
- 1
values(head)follows the active chain and returns its data. - 2
values(free, indices=True)follows the free chain and returns free-node indexes, not their unused data. - 3Both stop at −1. An empty chain returns an empty list.
- 4The final free cell must link to −1; linking it to 6 would read beyond the array.
values(head) returns active data; values(free, indices=True) returns free-node indexes, not their unused data. Both follow links and stop at −1. An empty chain returns an empty list. The final free cell must link to −1; linking it to 6 would read beyond the array.
Later, two values are stored: head = 0, free = 1. Read each chain by following Next, not by reading down the rows.
| Physical cell | Data | Next |
|---|---|---|
| 0 | 31 | 2 |
| 1 | unused | 3 |
| 2 | 14 | -1 |
| 3 | unused | 4 |
| 4 | unused | 5 |
| 5 | unused | -1 |
1 Follow head through the table. Which values does values(head) return?
2 Which indexes does values(free, indices=True) return?
3 Cell 2 links to −1. What does that tell you about 14?
- 131, 14
- 21, 3, 4, 5
- 314 is the last node of the active list
Linked-list search and insertion
Because the order lives in the links, adding a lantern never moves the others. Search follows the active chain from head. Append takes one cell from the free chain and links the old last node to it.
data and link have indexes 0–5; NULL = −1. head starts the active chain; free starts the unused chain.
def find(target): current = head while current != NULL: if data[current] == target: return current current = link[current] return NULL
def add_last(value): global head, free if free == NULL: return False new = free free = link[new] data[new] = value link[new] = NULL if head == NULL: head = new else: last = head while link[last] != NULL: last = link[last] link[last] = new return True
Append 27 after 31, 14
Watch the free chain give up its first cell. Work through the three steps, then find each change in blue in the second drawing.
Before: head = 0, free = 2; data[0] = 31, data[1] = 14. Active: 0 → 1 → −1. Free: 2 → 3 → 4 → 5 → −1.
- If the list is empty, assign head instead of a previous node’s link.
- If free is −1, return False before changing anything.
- To insert after a known node p, set link[new] to its old successor before setting link[p] to new.
1 After 27, add_last(8) runs. Which cell does 8 go into?
2 What is free after that?
3 Which link changes to connect 8 to the list, and to what?
- 1cell 3, the first free cell
- 24
- 3link[2] changes from −1 to 3
Linked-list deletion
To remove a lantern, the list only has to steer round it. Deletion bypasses the matching node, then returns it to the free list so the cell can be used again. Keep both previous and current during the search: the predecessor owns the link that must change.
1def delete(target): 2global head, free 3previous = NULL 4current = head 5while current != NULL and data[current] != target: 6previous = current 7current = link[current] 8if current == NULL: 9return False 10if previous == NULL: 11head = link[current] 12else: 13link[previous] = link[current] 14data[current] = None 15link[current] = free 16free = current 17return True
Delete the middle node without losing either chain
Deletion changes two chains, one at a time. Read the rows in order: bypass 14 first, then hand its cell to free.
| Stage | Active chain | Free chain |
|---|---|---|
| 31, 14, 27 stored | 0 → 1 → 2 → −1 | 3 → 4 → 5 → −1 |
| Bypass current = 1 | 0 → 2 → −1 | 3 → 4 → 5 → −1 |
| Release cell 1 | 0 → 2 → −1 | 1 → 3 → 4 → 5 → −1 |
- Deleting the head changes head. Deleting the tail copies its −1 link to the predecessor.
- Deleting the sole node makes head = −1.
- A missing key reaches null and leaves both chains unchanged.
- Clear the data for readable diagnostics; chain membership is determined by pointers.
1 After 14 is deleted, delete(31) runs. What is head now?
2 Give the free chain after that, as indexes.
3 Then delete(25) runs. What does it return?
- 12: 31 was the head, so head takes its link
- 20, 1, 3, 4, 5
- 3False: nothing changes
Binary-tree storage and search
A binary search tree lets one comparison skip a whole branch. It stores at most two child links per node: smaller IDs left, greater or equal IDs right. root = −1 means empty; a leaf has two null children.
The rows behind the drawing: each [index] in the drawing is a row here.
| Index | Left | ID | Right |
|---|---|---|---|
| 0 | 1 | 31 | -1 |
| 1 | 3 | 14 | 2 |
| 2 | 4 | 27 | -1 |
| 3 | -1 | 8 | -1 |
| 4 | 5 | 22 | -1 |
| 5 | -1 | 19 | -1 |
def tree_find(target): current = root while current != NULL: value = tree[current][1] if value == target: return current if target < value: current = tree[current][0] else: current = tree[current][2] return NULL
The search for 19, one node per row: compare, then take the left or right link the comparison picks.
current | ID there | next current | Comparison | |
|---|---|---|---|---|
| pass 1 | 0 | 31 | 1 | 19 < 31: go left to 1 |
| 19 < 31: go left to 1 | ||||
| pass 2 | 1 | 14 | 2 | 19 ≥ 14: go right to 2 |
| 19 ≥ 14: go right to 2 | ||||
| pass 3 | 2 | 27 | 4 | 19 < 27: go left to 4 |
| 19 < 27: go left to 4 | ||||
| pass 4 | 4 | 22 | 5 | 19 < 22: go left to 5 |
| 19 < 22: go left to 5 | ||||
| pass 5 | 5 | 19 | 19 = 19: return 5 | |
| 19 = 19: return 5 | ||||
- For 19, compare 31 → 14 → 27 → 22 → 19 and return cell 5.
- For 25, the same first four comparisons lead right from 22 to −1: absent.
- Searching costs O(h) for tree height h: O(log n) when balanced, O(n) when skewed.
For 19, compare 31 → 14 → 27 → 22 → 19 and return cell 5. For 25, the same first four comparisons lead right from 22 to −1: absent. Searching costs O(h) for tree height h: O(log n) when balanced, O(n) when skewed.
1 Search for 8. Which IDs are compared, and which cell is returned?
2 Search for 30. Which null link ends the search?
3 At most how many IDs does any search of this tree compare?
- 131, 14, 8; cell 3
- 2the right link of cell 2 (27), after 31, 14, 27; returns −1
- 35: one per level, down to 19
Binary-tree insertion
A search for a missing ID ends at an empty link, and that is exactly where the ID belongs. To insert, follow the key comparisons down to an empty child link and attach the new node there. Replacing a populated child would lose its whole subtree.
Tavren uses six cells and never deletes tree nodes. Insert IDs 31, 14, 27, 8, 22, 19, in that order, into the initially empty tree.
NULL = -1 tree = [[NULL, None, NULL] for i in range(6)] root = NULL next_free = 0
1def add_node(value): 2global root, next_free 3if next_free == len(tree): 4return False 5new = next_free 6tree[new] = [NULL, value, NULL] 7next_free = next_free + 1 8if root == NULL: 9root = new 10return True 11current = root 12while True: 13side = 0 if value < tree[current][1] else 2 14if tree[current][side] == NULL: 15tree[current][side] = new 16return True 17current = tree[current][side]
Trace the insertions
Inserting 19 is a search that ends on an empty link. Follow the blue path, then find the row where the link is empty.
current | ID there | side | link there | What happens | |
|---|---|---|---|---|---|
| pass 1 | 0 | 31 | left | 1 | 19 < 31: go left; follow to 1 |
| 19 < 31: go left; follow to 1 | |||||
| pass 2 | 1 | 14 | right | 2 | 19 ≥ 14: go right; follow to 2 |
| 19 ≥ 14: go right; follow to 2 | |||||
| pass 3 | 2 | 27 | left | 4 | 19 < 27: go left; follow to 4 |
| 19 < 27: go left; follow to 4 | |||||
| pass 4 | 4 | 22 | left | −1 | 19 < 22: go left; empty: tree[4][0] = 5 |
| 19 < 22: go left; empty: tree[4][0] = 5 | |||||
- 1The first ID, 31, makes cell 0 the root.
- 2Inserting 19 later follows 31 left, 14 right, 27 left, 22 left.
- 3Cell 5 is allocated; tree[4][0] = 5 connects it. next_free becomes 6, so the next insertion returns False.
- This allocation works because nodes are never removed: next_free advances through unused cells. A reusable free-node chain would be needed if deletion were allowed.
- Follow the task’s stated duplicate policy; this model sends equal keys right.
1 The tree is given a seventh cell and 25 is inserted after the six IDs. Which way does it go at each node?
2 Which link is set, and to what?
3 In the six-cell tree, what does add_node(41) return, and why?
- 1left at 31, right at 14, left at 27, right at 22
- 2tree[4][2] = 6, the right link of 22
- 3False: next_free is 6, equal to len(tree), so no cell is free
Stack implementation
Undo works backwards: the last check made is the first one taken back. A stack is last in, first out (LIFO). top is the index of the last occupied cell: −1 means empty; 5 means full in this six-cell array. Push and pop each take O(1) time.
1stack = [None] * 6 2top = -1 3 4def push(value): 5global top 6if top == len(stack) - 1: 7return False 8top = top + 1 9stack[top] = value 10return True 11 12def pop(): 13global top 14if top == -1: 15return None 16value = stack[top] 17stack[top] = None 18top = top - 1 19return value
Three snapshots of the six-cell array. Watch top: push moves it up a cell, pop reads the top cell and then moves it down.
- 1top = 2 points at 27. Pop saves and returns 27 before decreasing top to 1.
- 2The next pop returns 14. The value comes from the top cell each time.
- 3Test the boundary before changing top; a refused push or empty pop preserves the state.
When to use a stack
Tavren can undo checks in reverse order with a stack. It cannot use the same removal rule for requests that must be served in arrival order; that requires a queue.
1 An empty stack runs push(8), push(22), pop(), push(19). What is top?
2 What does the next pop return?
3 The stack is full (top = 5). What does push(41) return, and what happens to top?
- 11
- 219 (22 was popped earlier)
- 3False; top stays 5
Linear-queue implementation
Requests for lanterns must be served in the order they arrive. A linear queue advances towards the array’s final cell without wrapping. Both first and last start at −1; after insertion they identify the next removal and the last occupied position.
1line = [None] * 6 2first = -1 3last = -1 4 5def line_add(value): 6global first, last 7if last == len(line) - 1: 8return False 9last = last + 1 10line[last] = value 11if first == -1: 12first = 0 13return True 14 15def line_remove(): 16global first 17if first == -1 or first > last: 18return -1 19value = line[first] 20first = first + 1 21return value
Full and empty: two different tests
Three states of one queue. Compare where first and last sit when an insertion is refused and when a removal returns −1.
| State | first, last | Operation result |
|---|---|---|
| Six insertions | 0, 5 | Full: another insertion returns False. |
| Remove 31 and 14 | 2, 5 | Four remain; insertion still returns False. |
| Remove all six | 6, 5 | Empty: another removal returns −1. |
- Full tests the last array position; empty tests first > last (or first = −1 initially).
- Earlier freed cells are never reused in this implementation.
- A task may specify resetting pointers when the queue empties: follow that contract. The circular implementation later reuses freed cells; this linear model does not wrap or shift.
1 A fresh queue runs line_add(31), line_add(14), line_add(27), then line_remove(). Give first and last.
2 What does the next line_remove() return?
3 After six insertions and six removals, why does line_add still return False?
- 1first 1, last 2
- 214
- 3last is 5, the final array position; freed cells are not reused
Testing the linear queue
Functions that look right still have to be shown working. The queue functions need a main program that reads inputs, checks the values returned and shows the resulting state.
- Each test starts with six cells
line[0]toline[5]andfirst = last = −1. - line_add advances last then stores, setting first to 0 on the first insertion; it returns False at last = 5.
- line_remove returns line[first] then advances first, or −1 when empty. Freed cells are not reused.
Test a full queue
Seven inputs into six cells. The seventh must be refused, and the program must say so.
for attempt in range(7): value = int(input()) if not line_add(value): print("Full: refused", value) print("Stored", line) print("Pointers", first, last)
Full: refused 41 Stored [31, 14, 27, 8, 22, 19] Pointers 0 5
Test removals from another fresh queue
Four removals should come back in arrival order, and first should finish on the next value to serve.
for attempt in range(6): line_add(int(input())) for attempt in range(4): print("Removed", line_remove()) print("Next", line[first]) print("Pointers", first, last)
Removed 31 Removed 14 Removed 27 Removed 8 Next 22 Pointers 4 5
- Convert each input string to an integer before insertion.
- Test the Boolean return from insertion; checking the raw value would confuse a legitimate integer with success or failure.
- Each removal must use and output the returned value, rather than print an arbitrary array cell.
1 A fresh queue receives inputs 5, 6, 7, then two removals are printed. What is output?
2 What are first and last then?
3 Two more removals are printed. What do they show?
- 1Removed 5, Removed 6
- 2first 2, last 2
- 3Removed 7, then Removed -1: the queue is empty
Circular-queue implementation
A linear queue can report full while cells at its start lie empty. A queue is first in, first out (FIFO). front points at the next item to remove; rear points at the last item added; count distinguishes empty (0) from full (6). Freed cells are reused by wrapping around.
1queue = [None] * 6 2front = 0 3rear = -1 4count = 0 5 6def enqueue(value): 7global rear, count 8if count == len(queue): 9return False 10rear = (rear + 1) % len(queue) 11queue[rear] = value 12count = count + 1 13return True 14 15def dequeue(): 16global front, count 17if count == 0: 18return None 19value = queue[front] 20queue[front] = None 21front = (front + 1) % len(queue) 22count = count - 1 23return value
How the pointers wrap round
Two moments in the same queue. In the second, rear steps past cell 5 and wraps to cell 0, freed by the first dequeue.
- 1Modulo 6 maps the next position after 5 back to 0.
- 2Neither removal nor insertion shifts the other records, so both are O(1).
- 3Returning None on an empty queue gives the caller a distinct failure result.
Some designs make rear point to the next free cell instead. Read its definition before choosing the update order; the code here always advances rear before storing.
1 rear is 5 and the queue is not full. At which index does the next enqueue store its value?
2 front is 4 and count is 3. Which indexes hold the queue, in the order they will be served?
3 Why does the queue keep count as well as front and rear?
- 10: (5 + 1) MOD 6
- 24, 5, 0
- 3front and rear alone look the same when the queue is empty and when it is full
Circular-queue states and tests
Pointer positions alone do not tell the queue’s length. Trace front, rear and count together, then read active cells from front in FIFO order.
- Start with six empty cells, front = 0, rear = −1 and count = 0.
- Enqueue advances rear modulo 6, stores and increases count; dequeue reads front, advances it modulo 6 and decreases count.
- A full insertion returns False without change.
First the one enqueue where rear wraps, line by line.
| Line | Statement that runs | rear | queue[rear] | count | Writes | What happens |
|---|---|---|---|---|---|---|
| 3 | if count == len(queue): | test 4 = 6 is false: there is room | ||||
| test 4 = 6 is false: there is room | ||||||
| 5 | rear = (rear + 1) % len(queue) | 0 | rear 0 | (5 + 1) MOD 6 = 0 | ||
| (5 + 1) MOD 6 = 0 | ||||||
| 6 | queue[rear] = value | 31 | queue[rear] 31 | stored in cell 0, freed earlier | ||
| stored in cell 0, freed earlier | ||||||
| 7 | count = count + 1 | 5 | count 5 | 4 + 1 | ||
| 4 + 1 | ||||||
Then every operation as a row, with the queue read from front.
front | rear | count | FIFO order | Why | |
|---|---|---|---|---|---|
| Initially | 0 | -1 | 0 | empty | count 0: empty |
| count 0: empty | |||||
| Enqueue all six IDs | 0 | 5 | 6 | 31 14 27 8 22 19 | count 6: full |
| count 6: full | |||||
| Dequeue twice | 2 | 5 | 4 | 27 8 22 19 | 31 and 14 served; front moves to 2 |
| 31 and 14 served; front moves to 2 | |||||
| Enqueue 31, 14 | 2 | 1 | 6 | 27 8 22 19 31 14 | rear wraps: 5 → 0 → 1 |
| rear wraps: 5 → 0 → 1 | |||||
| Try enqueue 41 | 2 | 1 | 6 | 27 8 22 19 31 14 | count = 6: returns False, nothing changes |
| count = 6: returns False, nothing changes | |||||
| Operation | front, rear, count | FIFO order |
|---|---|---|
| Initially | 0, −1, 0 | empty |
| Enqueue all six IDs | 0, 5, 6 | 31 14 27 8 22 19 |
| Dequeue twice | 2, 5, 4 | 27 8 22 19 |
| Enqueue 31, 14 | 2, 1, 6 | 27 8 22 19 31 14 |
| Try enqueue 41 | 2, 1, 6 | unchanged: full |
The same operations as a program. Its printed front, rear and count should match the last two rows.
for value in [31, 14, 27, 8, 22, 19]: enqueue(value) print(dequeue(), dequeue()) enqueue(31) enqueue(14) print(front, rear, count) print(queue) print(enqueue(41))
31 14 2 1 6 [31, 14, 27, 8, 22, 19] False
Read the queue from front, not from index 0
- The final array happens to match its earlier physical contents. Its front has moved, so it now serves 27 first.
- Drain it six times: 27, 8, 22, 19, 31, 14. count becomes 0; another dequeue returns None. No stale value is served.
1 From the final state, dequeue runs three times. Which values are returned?
2 Then enqueue(41) runs. Give front, rear and count.
3 At which index is 41 stored?
- 127, 8, 22
- 2front 5, rear 2, count 4
- 32: the cell 27 was served from
Graphs and dictionaries as ADTs
Not every collection is a line of items. Some data is about connections; some is about looking a thing up by its key. A graph represents connections; a dictionary associates each unique key with a value. Both offer more than an unstructured sequence.
A graph models routes between hire counters
Four hire counters and the transfers allowed between them. Read each edge’s direction and its minutes.
- Each vertex is a counter; each edge is an allowed transfer. The arrow A → B permits only that direction.
- A weight records transfer minutes. An undirected graph would allow travel both ways along each edge.
- A cycle allows a route back to its start.
A program stores a graph in one of two ways. Choose by how many links each counter has.
| Representation | Stores | Useful when |
|---|---|---|
| Adjacency list | Neighbours of each vertex, with weights | There are few links per counter. |
| Adjacency matrix | A cell for every ordered vertex pair | Fast edge-existence checks matter. |
A dictionary models ID → record
lanterns = {31: [6, "available"], 14: [9, "on-loan"]} lanterns[22] = [12, "available"] print(lanterns[14]) print(25 in lanterns)
- Lookup uses a key rather than a sequence position. Updating an existing key replaces its associated value.
- A dictionary can be implemented by a list, search tree or hash table; its ADT contract does not guarantee one storage method. Hashing is developed in Unit 13.
1 Can a transfer go from B to A in the graph? Why?
2 What is the shortest time from C to B?
3 lanterns[14] = [9, "available"] runs next. What does print(lanterns[14]) show?
- 1no: the edge is directed A → B only, and no route leaves B
- 27 min: C → D → B (5 + 2)
- 3[9, 'available']: the value for key 14 is replaced
Testing a collection program
A program that works on one tidy example can still fail on an empty list or a full one. A practical task needs a complete program and observed results. Test operations in sequence, so later calls use the actual state produced by earlier calls.
- Begin with six empty data cells, link = [1, 2, 3, 4, 5, −1], head = −1 and free = 0.
- add_last appends; find returns a cell index or −1; delete releases the matching cell to the front of the free chain.
for value in [31, 14, 27, 8, 22, 19]: print(add_last(value), end=" ") print() print("Active", values(head)) print("Full", add_last(41)) print("Find", find(22), find(25)) delete(27) delete(31) print("Active", values(head)) print("Pointers", head, free) print("Free cells", values(free, indices=True))
True True True True True True Active [31, 14, 27, 8, 22, 19] Full False Find 4 -1 Active [14, 8, 22, 19] Pointers 1 0 Free cells [0, 2]
One run is not enough: plan a test of each kind, and say what it should show.
| Test category | What to inspect |
|---|---|
| Normal | Found index, removed value and logical output order. |
| Boundary | Empty list; first/last item; exactly full storage; one item left. |
| Failure | Absent key or full insert: failure result and unchanged state. |
| Reuse | A deleted node is available again; queue wraps into freed cells. |
Which structure for which job
- Repeated ID lookup on a mostly fixed catalogue: a sorted array supports O(log n) binary search, but inserting in order may move O(n) records.
- A linked list edits links cheaply once the predecessor is known, but finding that position costs O(n).
- A tree’s cost depends on its height. FIFO requests use a queue; undo uses a stack.
- All these six-cell representations reserve O(n) storage.
For repeated ID lookup on a mostly fixed catalogue, a sorted array supports O(log n) binary search, but inserting in order may move O(n) records. A linked list edits links cheaply once the predecessor is known, but finding that position costs O(n). A tree’s cost depends on height. FIFO requests use a queue; undo uses a stack. All these six-cell representations reserve O(n) storage.
1 After the driver, add_last(41) runs. What does it return?
2 What does values(head) return then, and what is free?
3 delete(25) is one test in the plan. Which category is it, and what should it show?
- 1True: cell 0 was free
- 2[14, 8, 22, 19, 41]; free = 2
- 3failure: it returns False and both chains are unchanged