Skip to content

9618 · Unit 22 · Papers 3–4: Theory and practical programming

Searching, sorting and data structures.

9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Bubble sort

§19.1 · Algorithms

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.

Python
 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.

Pass 1: compare each pair of neighbours, left to right
j = 031 > 14: swap03111422738422519
j = 131 > 27: swap01413122738422519
j = 231 > 8: swap01412723138422519
j = 331 > 22: swap01412728331422519
j = 431 > 19: swap01412728322431519
after pass 131 is in its final place01412728322419531
the pair comparedin its final place
One comparison: pass 1, j = 0
The whole record moves, so its wattage stays with its ID.
LineStatement that runstempitems[j]items[j + 1]swappedWritesWhat happens
7if items[j][0] > items[j + 1][0]:test 31 > 14 is true: swap
test 31 > 14 is true: swap
8temp = items[j][31, 6]temp [31, 6]save the left record
save the left record
9items[j] = items[j + 1][14, 9]items[j] [14, 9]copy the right record left
copy the right record left
10items[j + 1] = temp[31, 6]items[j + 1] [31, 6]the saved record goes right
the saved record goes right
11swapped = TrueTrueswapped Truea 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.

endComparesSwapsswappedIDs after the passWhat it settled
start5True31 14 27 8 22 19lines 2 and 3
lines 2 and 3
pass 1455True14 27 8 22 19 3131 is now in place at index 5
31 is now in place at index 5
pass 2343True14 8 22 19 27 3127 is now in place at index 4
27 is now in place at index 4
pass 3232True8 14 19 22 27 3122 is now in place at index 3
22 is now in place at index 3
pass 4120False8 14 19 22 27 31no swaps: swapped stays False, so the loop stops
no swaps: swapped stays False, so the loop stops
PassComparisonsSwapsIDs after pass
15514 27 8 22 19 31
24314 8 22 19 27 31
3328 14 19 22 27 31
4208 14 19 22 27 31

How the loop controls work

Two small details stop the sort doing wasted work:

  1. 1
    end shrinks by 1 after each pass: the last ID of that pass is already in place.
  2. 2
    swapped is reset to False at the start of each pass. A pass with no swaps proves the order is correct, so the loop stops.
  3. 3
    range(end) stops at end − 1, so j + 1 stays inside the active range.
  4. 4
    Swap the whole record so its wattage stays attached. Equal IDs are never swapped, so they keep their order. Changing > to < sorts descending.
Your turn

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?

  1. 1
    5, 9, 3, 12
  2. 2
    3
  3. 3
    3: end reached 0 (the swaps per pass are 3, 1, 1)
Tick what you can do now
Practise with s26/22 Q5(b)(i), (b)(ii) (prerequisite bubble-sort algorithm)
2 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Insertion sort

§19.1 · Algorithms

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.

Python
 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.

Each pass: save the next record, shift larger ones right, drop it in the gap
startindex 0 is a sorted part of one03111422738422519
pos = 1save 14 · shift 3101413122738422519
pos = 2save 27 · shift 3101412723138422519
pos = 3save 8 · shift 31, 27, 1408114227331422519
pos = 4save 22 · shift 31, 2708114222327431519
pos = 5save 19 · shift 31, 27, 2208114219322427531
the sorted partthe saved record in its gapshifted one place right
One pass, line by line: pos = 4
The blue row of the whole sort, as the lines run.
LineStatement that runssavedjitems[j + 1]WritesWhat happens
3saved = items[pos][22, 12]saved [22, 12]save the record at index 4
save the record at index 4
4j = pos - 13j 3start just left of it
start just left of it
5while (j >= 0 and items[j][field] > saved[field]):test 31 > 22 is true
test 31 > 22 is true
7items[j + 1] = items[j][31, 6]items[j + 1] [31, 6]31 shifts right to index 4
31 shifts right to index 4
8j = j - 12j 2
5while (j >= 0 and items[j][field] > saved[field]):test 27 > 22 is true
test 27 > 22 is true
7items[j + 1] = items[j][27, 12]items[j + 1] [27, 12]27 shifts right to index 3
27 shifts right to index 3
8j = j - 11j 1
5while (j >= 0 and items[j][field] > saved[field]):test 14 > 22 is false: stop shifting
test 14 > 22 is false: stop shifting
9items[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.

savedShifted rightLands atIDs after the passWhy
pos 11431014 31 27 8 22 1931 is larger than 14: shift right
31 is larger than 14: shift right
pos 22731114 27 31 8 22 1931 is larger than 27: shift right
31 is larger than 27: shift right
pos 3831, 27, 1408 14 27 31 22 1931, 27, 14 are larger than 8: shift right
31, 27, 14 are larger than 8: shift right
pos 42231, 2728 14 22 27 31 1931, 27 are larger than 22: shift right
31, 27 are larger than 22: shift right
pos 51931, 27, 2228 14 19 22 27 3131, 27, 22 are larger than 19: shift right
31, 27, 22 are larger than 19: shift right
Saved IDShift rightIDs after insertion
143114 31 27 8 22 19
273114 27 31 8 22 19
831, 27, 148 14 27 31 22 19
2231, 278 14 22 27 31 19
1931, 27, 228 14 19 22 27 31

Sort on another field

A sort can order the records on any field, not only the ID:

  1. 1
    insertion(items, 0) orders by ID; insertion(items, 1) orders by wattage. By watts the IDs become 31, 8, 14, 19, 27, 22.
  2. 2
    The strict > leaves equal watts in their arrival order.
  3. 3
    Checking j >= 0 before reading items[j] stops the loop crossing the lower bound.
  4. 4
    For parallel arrays, save both ID and wattage, shift both at each index, then restore both at j + 1.
Your turn

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?

  1. 1
    4, 9, 7, 2
  2. 2
    9, 7, 4
  3. 3
    5
Tick what you can do now
Practise with s26/31 Q10(a), (b), (c); s26/42 Q1(c)(i), (c)(ii), (c)(iii) (transfer: return the sorted array)
3 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Comparing search and sort costs

§19.1 · Algorithms

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.

AlgorithmBest timeWorst timeAuxiliary space
Linear searchO(1)O(n)O(1)
Binary search, iterativeO(1)O(log n)O(1)
Bubble, early exitO(n)O(n²)O(1)
Insertion sortO(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.

15 items, key absent: candidates before each testtest 115test 27test 33test 41
  • 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 inputSix itemsTwelve items
Already ordered5 key comparisons11 key comparisons
Reverse order15 shifts66 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.
Your turn

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?

  1. 1
    7
  2. 2
    200: every one
  3. 3
    28: 8 × 7 ÷ 2
Tick what you can do now
Practise with s26/31 Q10(b), (c); s26/32 Q10(a); s26/33 Q10(b)
5 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Counting and sorting strings

§19.1 · Algorithms

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.

Count “Available”: compare lower-case forms
statusesas entered0Repair1AVAILABLE2On-loan3available
.lower()target “available”0repair1availablematch2on-loan3availablematch
sortedinsertion_text returns this0available1available2on-loan3repair
match: total + 1no match: keep going
Python · count every match
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.

Python · return the sorted array
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
Python · main program
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.

Your turn

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?

  1. 1
    2
  2. 2
    0: “Repair” and “REPAIR” no longer equal “repair”
  3. 3
    ['available', 'lost', 'repair']
Tick what you can do now
Practise with s26/42 Q1(c)(i), (c)(ii), (c)(iii); s26/43 Q1(e)
6 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Sorting strings by length

§19.1 · Algorithms

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.

Python · sort in place by length
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.

Bubble passes on length: the longest string moves to the end
startlength under each0available91repair62on-loan73repair6
pass 13 swaps0repair61on-loan72repair63available9
pass 21 swap0repair61repair62on-loan73available9
pass 30 swaps0repair61repair62on-loan73available9
in its final place

Now count the swaps. The loop stops only after a pass that makes none.

ComparesSwapsswappedStrings after the passWhat it settled
pass 133Truerepair, on-loan, repair, availableavailable (9 characters) is in place
available (9 characters) is in place
pass 221Truerepair, repair, on-loan, availableon-loan (7 characters) is in place
on-loan (7 characters) is in place
pass 310Falserepair, repair, on-loan, availableno swaps: only now can the early exit stop the loop
no swaps: only now can the early exit stop the loop
Python · main program and length output
statuses = ["available", "repair", "on-loan", "repair"]
print("Before", statuses)
bubble_length(statuses)
print("After", statuses)
for value in statuses:
print(value, len(value))
PassStrings after passSwaps
1repair, on-loan, repair, available3
2repair, repair, on-loan, available1
3repair, repair, on-loan, available0
  • 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.
Your turn

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?

  1. 1
    lost, repair, available
  2. 2
    2
  3. 3
    repair: equal lengths are not swapped, so repair keeps its place before signal
Tick what you can do now
Practise with s26/43 Q1(f)(i), (f)(ii), (f)(iii)
7 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

ADT interfaces and implementations

§19.1 · Algorithms

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.

Stack311427toplast in, first out
Queue311427frontrearfirst in, first out
Linked list311427each node links on
Binary search tree221431smaller IDs go left

Start from what Tavren needs. The need picks the ADT and its operations; only then choose how to build it.

Tavren needADT and operationsImplementation choice
Most recent return checked firstStack: push, pop, isEmptyArray and top index
Requests served in arrival orderQueue: enqueue, dequeueCircular array and pointers
Editable ordered route of IDsLinked list: find, insert, deleteNode records and links
Find an ID by ordered branchingBinary search tree: find, insertLeft/data/right node records

Build a stack from a linked list

1
The linked list’s head is the stack top.
2
Push by allocating a free node, linking it to the old head, then making it head.
3
Pop by returning the head value, advancing head, and releasing the old node.
  • 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.

OperationFailure result
Insertion refusedFalse
Unsuccessful search−1
Stack pop or circular-queue dequeue when emptyNone
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.

Your turn

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?

  1. 1
    a queue (first in, first out)
  2. 2
    a stack (last in, first out)
  3. 3
    nothing it can see: push and pop still behave LIFO; only the implementation changed
Tick what you can do now
8 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Linked-list storage

§19.1 · Algorithms

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.

Python · empty active list, all cells free
 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. 1
    values(head) follows the active chain and returns its data.
  2. 2
    values(free, indices=True) follows the free chain and returns free-node indexes, not their unused data.
  3. 3
    Both stop at −1. An empty chain returns an empty list.
  4. 4
    The 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 cellDataNext
0312
1unused3
214-1
3unused4
4unused5
5unused-1
The same six cells as two chainshead= 0[0]312[2]14−1−1free= 1[1]–3[3]–4[4]–5[5]–−1−1
Separate stored state · follow next pointershead = 0index 0value 31index 2value 14−1Free route: boxes show indexesfree = 11345−1Each cell belongs to exactly one chain.
Your turn

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?

  1. 1
    31, 14
  2. 2
    1, 3, 4, 5
  3. 3
    14 is the last node of the active list
Tick what you can do now
Practise with s26/42 Q3(a), (b)(i), (b)(ii)
9 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Linked-list search and insertion

§19.1 · Algorithms

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.

Python · search the active chain
def find(target):
current = head
while current != NULL:
if data[current] == target:
return current
current = link[current]
return NULL
Python · append using data, link, head and free
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: 31, 14 storedhead= 0[0]311[1]14−1−1free= 2[2]–3[3]–4[4]–5[5]–−1−1

Before: head = 0, free = 2; data[0] = 31, data[1] = 14. Active: 0 → 1 → −1. Free: 2 → 3 → 4 → 5 → −1.

1
Reserve cell new = 2; advance free to 3 before overwriting link[2].
2
Store 27 in data[2] and set link[2] = −1.
3
Follow head to last = 1; set link[1] = 2. Active: 0 → 1 → 2 → −1; free: 3 → 4 → 5 → −1.
After append 27: blue = changedhead= 0[0]311[1]142[2]27−1−1free= 3[3]–4[4]–5[5]–−1−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.
Your turn

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?

  1. 1
    cell 3, the first free cell
  2. 2
    4
  3. 3
    link[2] changes from −1 to 3
Tick what you can do now
Practise with s26/42 Q3(c)(i), (c)(ii), (c)(iii)
10 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Linked-list deletion

§19.1 · Algorithms

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.

Python
 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

Before: 31, 14, 27 stored; 14 (blue) is deletedhead= 0[0]311[1]142[2]27−1−1free= 3[3]–4[4]–5[5]–−1−1

Deletion changes two chains, one at a time. Read the rows in order: bypass 14 first, then hand its cell to free.

StageActive chainFree chain
31, 14, 27 stored0 → 1 → 2 → −13 → 4 → 5 → −1
Bypass current = 10 → 2 → −13 → 4 → 5 → −1
Release cell 10 → 2 → −11 → 3 → 4 → 5 → −1
After delete(14): blue = changedhead= 0[0]312[2]27−1−1free= 1[1]–3[3]–4[4]–5[5]–−1−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.
Your turn

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?

  1. 1
    2: 31 was the head, so head takes its link
  2. 2
    0, 1, 3, 4, 5
  3. 3
    False: nothing changes
Tick what you can do now
Practise with s26/23 Q6(c)(ii), (d) (prerequisite linked-list operations)
11 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Binary-tree insertion

§19.1 · Algorithms

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.

Python · initialise empty tree storage
NULL = -1
tree = [[NULL, None, NULL] for i in range(6)]
root = NULL
next_free = 0
Python · allocate and attach one node
 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.

Insert 19: follow the comparisons, attach at the empty linkleftleftrightleftleft31[0]14[1]8[3]27[2]22[4]19[5]
currentID theresidelink thereWhat happens
pass 1031left119 < 31: go left; follow to 1
19 < 31: go left; follow to 1
pass 2114right219 ≥ 14: go right; follow to 2
19 ≥ 14: go right; follow to 2
pass 3227left419 < 27: go left; follow to 4
19 < 27: go left; follow to 4
pass 4422left−119 < 22: go left; empty: tree[4][0] = 5
19 < 22: go left; empty: tree[4][0] = 5
  1. 1
    The first ID, 31, makes cell 0 the root.
  2. 2
    Inserting 19 later follows 31 left, 14 right, 27 left, 22 left.
  3. 3
    Cell 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.
Your turn

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?

  1. 1
    left at 31, right at 14, left at 27, right at 22
  2. 2
    tree[4][2] = 6, the right link of 22
  3. 3
    False: next_free is 6, equal to len(tree), so no cell is free
Tick what you can do now
Practise with s26/43 Q3(a), (b), (c), (d)(i)
13 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Stack implementation

§19.1 · Algorithms

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.

Python
 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.

push 31, 14, 27[0]31[1]14[2]27[3][4][5]top= 2pop[0]31[1]14[2][3][4][5]top= 1returns 27pop again[0]31[1][2][3][4][5]top= 0returns 14
Push 31, then 14, then 27[0]31[1]14[2]27top
  1. 1
    top = 2 points at 27. Pop saves and returns 27 before decreasing top to 1.
  2. 2
    The next pop returns 14. The value comes from the top cell each time.
  3. 3
    Test 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.

Your turn

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?

  1. 1
    1
  2. 2
    19 (22 was popped earlier)
  3. 3
    False; top stays 5
Tick what you can do now
Practise with s25/42 Q1(b), (c) (older paper: implement push and pop)
14 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Linear-queue implementation

§19.1 · Algorithms

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.

Python
 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.

Six insertions: full, another insertion returns False[0]31[1]14[2]27[3]8[4]22[5]19first = 0last = 5Remove 31 and 14 (amber: removed, never reused)[0]31[1]14[2]27[3]8[4]22[5]19first = 2last = 5Remove all six: first > last, so removal returns −1[0]31[1]14[2]27[3]8[4]22[5]19last = 5first = 6 (past the end)
Statefirst, lastOperation result
Six insertions0, 5Full: another insertion returns False.
Remove 31 and 142, 5Four remain; insertion still returns False.
Remove all six6, 5Empty: 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.
Your turn

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?

  1. 1
    first 1, last 2
  2. 2
    14
  3. 3
    last is 5, the final array position; freed cells are not reused
Tick what you can do now
Practise with s26/41 Q1(a), (b), (c)(i), (d), (e)(i)
15 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Testing the linear queue

§19.1 · Algorithms

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] to line[5] and first = 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.

Python · main program using the linear-queue functions
for attempt in range(7):
value = int(input())
if not line_add(value):
print("Full: refused", value)
print("Stored", line)
print("Pointers", first, last)
Inputs 31, 14, 27, 8, 22, 19, 41 · observed output
Full: refused 41
Stored [31, 14, 27, 8, 22, 19]
Pointers 0 5
Stored after the first test: 41 refused[0]31[1]14[2]27[3]8[4]22[5]19first = 0last = 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.

Python · main program from a fresh queue
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)
Inputs 31, 14, 27, 8, 22, 19 · observed output
Removed 31
Removed 14
Removed 27
Removed 8
Next 22
Pointers 4 5
After four removals: next is line[4][0]31[1]14[2]27[3]8[4]22[5]19first = 4last = 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.
Your turn

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?

  1. 1
    Removed 5, Removed 6
  2. 2
    first 2, last 2
  3. 3
    Removed 7, then Removed -1: the queue is empty
Tick what you can do now
Practise with s26/41 Q1(c)(i), (c)(ii), (e)(i), (e)(ii)
16 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Circular-queue implementation

§19.1 · Algorithms

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.

Python
 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.

Six enqueued, two dequeued: front 2, rear 5, count 4[0][1][2]27[3]8[4]22[5]19front = 2rear = 5(5 + 1) MOD 6 = 0enqueue(31): rear wraps to 0, count 5[0]31[1][2]27[3]8[4]22[5]19rear = 0front = 2
  1. 1
    Modulo 6 maps the next position after 5 back to 0.
  2. 2
    Neither removal nor insertion shifts the other records, so both are O(1).
  3. 3
    Returning 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.

Your turn

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?

  1. 1
    0: (5 + 1) MOD 6
  2. 2
    4, 5, 0
  3. 3
    front and rear alone look the same when the queue is empty and when it is full
Tick what you can do now
Practise with s26/21 Q7(b)(i), (b)(ii), (b)(iii) (prerequisite)
17 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Circular-queue states and tests

§19.1 · Algorithms

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.

enqueue(31), line by line: the wrap
The first half of the ENQUEUE 31, 14 row; enqueue(14) then moves rear to 1 and count to 6.
LineStatement that runsrearqueue[rear]countWritesWhat happens
3if count == len(queue):test 4 = 6 is false: there is room
test 4 = 6 is false: there is room
5rear = (rear + 1) % len(queue)0rear 0(5 + 1) MOD 6 = 0
(5 + 1) MOD 6 = 0
6queue[rear] = value31queue[rear] 31stored in cell 0, freed earlier
stored in cell 0, freed earlier
7count = count + 15count 54 + 1
4 + 1

Then every operation as a row, with the queue read from front.

frontrearcountFIFO orderWhy
Initially0-10emptycount 0: empty
count 0: empty
Enqueue all six IDs05631 14 27 8 22 19count 6: full
count 6: full
Dequeue twice25427 8 22 1931 and 14 served; front moves to 2
31 and 14 served; front moves to 2
Enqueue 31, 1421627 8 22 19 31 14rear wraps: 5 → 0 → 1
rear wraps: 5 → 0 → 1
Try enqueue 4121627 8 22 19 31 14count = 6: returns False, nothing changes
count = 6: returns False, nothing changes
Operationfront, rear, countFIFO order
Initially0, −1, 0empty
Enqueue all six IDs0, 5, 631 14 27 8 22 19
Dequeue twice2, 5, 427 8 22 19
Enqueue 31, 142, 1, 627 8 22 19 31 14
Try enqueue 412, 1, 6unchanged: full

The same operations as a program. Its printed front, rear and count should match the last two rows.

Python · driver using the circular-queue functions
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))
Observed output
31 14
2 1 6
[31, 14, 27, 8, 22, 19]
False

Read the queue from front, not from index 0

Final state: front = 2, so 27 is served first[0]31[1]14[2]27[3]8[4]22[5]19rear = 1front = 2
  • 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.
Your turn

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?

  1. 1
    27, 8, 22
  2. 2
    front 5, rear 2, count 4
  3. 3
    2: the cell 27 was served from
Tick what you can do now
Practise with s26/21 Q7(b)(i), (b)(ii), (b)(iii) (prerequisite)
18 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Graphs and dictionaries as ADTs

§19.1 · Algorithms

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.

4 min3 min5 min2 minABCD
  • 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.

RepresentationStoresUseful when
Adjacency listNeighbours of each vertex, with weightsThere are few links per counter.
Adjacency matrixA cell for every ordered vertex pairFast edge-existence checks matter.

A dictionary models ID → record

Python
lanterns = {31: [6, "available"], 14: [9, "on-loan"]}
lanterns[22] = [12, "available"]
print(lanterns[14])
print(25 in lanterns)
keyvalue31[6, 'available']14[9, 'on-loan']22[12, 'available']
  • 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.
Your turn

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?

  1. 1
    no: the edge is directed A → B only, and no route leaves B
  2. 2
    7 min: C → D → B (5 + 2)
  3. 3
    [9, 'available']: the value for key 14 is replaced
Tick what you can do now
Practise with s25/32 Q6(a) (older paper: graph structure)
19 / 20
9618 · Unit 22 · Searching, sorting and data structures
Revisionbyexamplicity

Testing a collection program

§19.1 · Algorithms

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.
Python · driver using the linked-list functions
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))
Observed output
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]
After the driver: blue = changed by the two deletionshead= 1[1]143[3]84[4]225[5]19−1−1free= 0[0]–2[2]–−1−1

One run is not enough: plan a test of each kind, and say what it should show.

Test categoryWhat to inspect
NormalFound index, removed value and logical output order.
BoundaryEmpty list; first/last item; exactly full storage; one item left.
FailureAbsent key or full insert: failure result and unchanged state.
ReuseA 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.

Your turn

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?

  1. 1
    True: cell 0 was free
  2. 2
    [14, 8, 22, 19, 41]; free = 2
  3. 3
    failure: it returns False and both chains are unchanged
Tick what you can do now
Practise with s26/42 Q3(c)(ii), (c)(iii); s26/43 Q3(d)(i), (d)(ii)
20 / 20