Computational
Thinking 6
Sorting lists: inserting into a sorted list, insertion sort and sorting records. Then a full application: grading Maths and Physics by quartile and testing whether students who do well in Maths also do well in Physics.
Chapters
- 01Inserting into a Sorted ListSorting lists
- 02Insertion SortSorting lists
- 03Inserting Records: the Library ExampleSorting lists
- 04The Hypothesis and the Marks ListsCorrelating performance
- 05Assigning Grades by QuartileCorrelating performance
- 06Testing the HypothesisCorrelating performance
- 07Week 6 Summary SheetAll topics
Inserting into a Sorted List
SortedListInsert: copy items until the first bigger one, insert, copy the rest.
Week 5 built lists and walked through them. This week the lists are kept in order, starting with the most basic step: putting one new value into a list that is already sorted.
1.1Why sort lists at all?
A sorted list makes a bunch of later problems almost free to solve:
- Finding the top few values: they sit at one end of the list.
- Spotting duplicates: equal values end up next to each other.
- Splitting a class into performance bands (top quarter, next quarter, and so on). This is exactly what the second half of these notes does.
1.2The idea
Say you already have a list in ascending order and you want to drop a new value into it without messing up the order. Walk through the sorted list one item at a time, copying each item into a new list, until you hit the first item that is bigger than the value you are inserting. Slot your value in right there, then copy over whatever is left.
1.3The procedure SortedListInsert(l, x)
Procedure SortedListInsert(l, x)
newList = []
inserted = False
foreach z in l {
if (not(inserted)) {
if (x < z) {
newList = newList ++ [x]
inserted = True
}
}
newList = newList ++ [z]
}
if (not(inserted)) {
newList = newList ++ [x]
}
return(newList)
End SortedListInsertnewListis built from scratch; the originallis never changed.newList = newList ++ [x]adds x the moment its spot is found.newList = newList ++ [z]copies every original item across exactly once, whether or not x was just inserted.- The
insertedflag makes sure x is only ever added once, even though the loop keeps running afterwards.
Inserting into a sorted list takes one pass: copy items across until you find where the new one belongs, insert it, then copy the rest.
1.4Trace: SortedListInsert([10, 20, 30, 40], 25)
| Pass | z | inserted before | Test x < z | What happens | newList after |
|---|---|---|---|---|---|
| 1 | 10 | False | 25 < 10: False | copy 10 | [10] |
| 2 | 20 | False | 25 < 20: False | copy 20 | [10, 20] |
| 3 | 30 | False | 25 < 30: True | insert 25, copy 30 | [10, 20, 25, 30] |
| 4 | 40 | True | not checked | copy 40 | [10, 20, 25, 30, 40] |
| after | True | final if skipped | [10, 20, 25, 30, 40] |
The test x < z is evaluated only 3 times: once inserted is True, the outer if (not(inserted)) skips it.
1.5Boundary cases to keep in mind
| Case | What happens in the loop | Where x ends up |
|---|---|---|
l is empty | the loop body never runs | appended by the final if |
x is smaller than everything in l | x < z is True on the first item | right at the front |
x is larger than everything in l | x < z is never True | appended at the end by the final if |
x < z), so a value equal to an existing item goes after it: inserting 20 into [10, 20, 30] gives [10, 20, 20, 30] with the new 20 second. With numbers you cannot tell the two 20s apart, but with records (Chapter 3) the order of ties becomes visible.1.6Going deeper
- The result always has one more item (extra). Every z is copied once and x is added once, so
length(newList)=length(l)+1. - The final if has two jobs (extra). It covers both the empty list and "x is the largest". Leaving it out would silently drop x in both cases.
- Comparisons (extra). The number of
x < ztests is the position where x lands, plus one, unless x goes at the end, in which case it islength(l). - Why a new list? Lists here are built with
++; there is no "insert in the middle" operation, so the list is rebuilt around x.
1.7Exam tips and common mistakes
- Trace with columns: z, inserted, the test, and newList after the pass.
- Check the three boundary cases whenever you are asked to modify the procedure.
- Putting
newList = newList ++ [z]inside theelse: then z is lost on the pass where x is inserted. - Forgetting the final
if (not(inserted)), which drops x when it is the largest or l is empty. - Thinking
x < zis tested on every pass; after insertion it is skipped.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
Let l = [10, 20, 30, 40]. What does SortedListInsert(l, 25) return?
[10, 20, 30, 40, 25][10, 20, 25, 30, 40][25, 10, 20, 30, 40][10, 25, 20, 30, 40]x goes in front of the first bigger item.
- The first item bigger than 25 is 30.
- Answer: option 2.
Numerical Answer Type (NAT).
With l = [10, 20, 30, 40], how many times is x < z evaluated in SortedListInsert(l, 25)?
After insertion the test is skipped.
- Tested against 10, 20 and 30; on 40
insertedis already True. - Answer: 3
Numerical Answer Type (NAT).
With l = [10, 20, 30, 40], how many times is x < z evaluated in SortedListInsert(l, 50)?
No item is bigger than 50.
- The test is False on all four items, and 50 is appended by the final
if. - Answer: 4
Multiple Choice Question (MCQ): choose the one correct option.
With l = [10, 20, 30], where does the new 20 go in SortedListInsert(l, 20)?
The test is strict.
20 < 20is False, so the old 20 is copied first;20 < 30is True, so the new 20 goes in front of 30.- Answer: option 3.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about SortedListInsert.
inserted flag makes sure x is added only onceif runs only when l is emptyThink about the flag and the final if.
- 1, 2 and 4 are true. The final
ifalso runs when x is larger than every item (statement 3 is false). - Answer: options 1, 2 and 4.
Duplicates side by side
Bands by position
Stop at the first bigger item
Insert, then copy the rest
x added only once
Test skipped afterwards
3 tests
[10, 20, 25, 30, 40]
Smallest: front
Largest: end
New equal value goes after
Matters for records
Insertion Sort
InsertionSort: insert every item into a growing sorted list, kept sorted by an invariant.
Once you can insert one item into an already-sorted list, sorting a whole list is just repeating that step.
2.1The procedure InsertionSort(l)
Start with an empty list, and insert every item of the original list into it, one by one.
Procedure InsertionSort(l)
sortedList = []
foreach z in l {
sortedList = SortedListInsert(sortedList, z)
}
return(sortedList)
End InsertionSort2.2Trace: InsertionSort([30, 10, 40, 20])
| z | Where it goes | sortedList after |
|---|---|---|
| 30 | empty list: appended | [30] |
| 10 | in front of 30 | [10, 30] |
| 40 | larger than all: appended | [10, 30, 40] |
| 20 | in front of 30 | [10, 20, 30, 40] |
2.3Why this works: the invariant
An empty list counts as sorted (there is nothing to be out of order). SortedListInsert keeps a sorted list sorted after adding one item. So sortedList stays sorted after every single loop step, and by the time the loop ends, the whole thing is sorted.
An invariant is a statement that is true before the loop and stays true after every pass. Checking it once at the start and once for a single pass is enough to trust the whole loop.
2.4Ascending or descending
This sorts in ascending order because SortedListInsert compares with x < z. Flip that one test and the exact same procedure sorts in descending order:
if (x > z) { // was: if (x < z)With x > z, x goes in front of the first smaller item: [30, 10, 40, 20] becomes [40, 30, 20, 10].
2.5How much work? (extra)
The lecture does not count comparisons for insertion sort, but it is a good use of Week 4's counting. Each insert tests x < z until it finds the spot. The total depends on the input order:
| Input (6 items) | Tests per insert | Total tests of x < z |
|---|---|---|
[1, 2, 3, 4, 5, 6] (already sorted) | 0, 1, 2, 3, 4, 5 | 15 = ½ × 6 × 5 |
[6, 5, 4, 3, 2, 1] (reverse sorted) | 0, 1, 1, 1, 1, 1 | 5 |
[30, 10, 40, 20] (4 items) | 0, 1, 2, 2 | 5 |
½ × N × (N − 1) tests, the same quadratic count as comparing all pairs in Week 4. A reverse-sorted input is its best case: each new item is smaller than the first one. (Counts from running the pseudocode.)2.6Same idea, applied to records
Real data usually is not a bare list of numbers; it is a list of records. Take a library of 1000 books: each book is a pair [SeqNo, Pages], and the list books is kept sorted by page count, ascending. Inserting a new book means comparing page counts, but the whole pair is carried along: the same insertion idea, comparing one field of a record instead of a plain value. Chapter 3 walks through exactly that.
2.7Going deeper
- Stability (extra). Because
x < zis strict, items with equal keys keep their original order: a later equal item goes after an earlier one. Sorts with this property are called stable. With<=(Chapter 3) equal items would come out in reverse order of arrival. - Swap the procedure, keep the sort.
InsertionSortonly callsSortedListInsert. Change how that one procedure compares (descending, or by a field of a pair) and the sort changes with it. Chapter 4 does exactly this. - A new list again (extra). The original
lis not changed; the sorted version is a new list.
2.8Exam tips and common mistakes
- Write sortedList after every insert; one line per item of the input.
- To count tests, count for each insert separately and add them up.
- Forgetting that sortedList starts as
[], not as the first item. - Assuming a sorted input is the easy case for this version.
- Changing
x < ztox > zand still expecting ascending order.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
Sorting [30, 10, 40, 20] with InsertionSort, what is sortedList after three items have been inserted?
[10, 30, 40][30, 10, 40][10, 20, 30][10, 20, 30, 40]Insert 30, then 10, then 40.
[30], then[10, 30], then[10, 30, 40].- Answer: option 1.
Numerical Answer Type (NAT).
Let l = [1, 2, 3, 4, 5, 6]. How many times is x < z evaluated by InsertionSort(l)?
Each new item is the largest so far.
- The inserts make 0, 1, 2, 3, 4 and 5 tests.
0 + 1 + 2 + 3 + 4 + 5 = 15.- Answer: 15
Numerical Answer Type (NAT).
Let l = [6, 5, 4, 3, 2, 1]. How many times is x < z evaluated by InsertionSort(l)?
Each new item is smaller than the first item.
- The first insert makes 0 tests; each of the other five makes 1.
- Answer: 5
Multiple Choice Question (MCQ): choose the one correct option.
Which change to SortedListInsert makes InsertionSort sort in descending order?
[0]x < z by x > zz ++ xx should go in front of the first smaller item.
- Replace
x < zbyx > z; nothing else changes. - Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about InsertionSort.
What is true after every pass?
- 1, 2 and 3 are true. The input list is not changed (statement 4 is false).
- Answer: options 1, 2 and 3.
Insert every item
Return sortedList
[30] → [10, 30]
→ [10, 20, 30, 40]
Each insert keeps it sorted
So the end is sorted
Compare a field: records
Sorted input: ½ × N × (N − 1) tests
Inserting Records: the Library Example
Insert(X, books): the same insertion idea, comparing one field of a record.
The same insertion logic works on records. The library example keeps a list of books sorted by their number of pages.
3.1Books as pairs
Each book in the list is a pair [SeqNo, Pages], and books is kept sorted by page count, ascending. To insert a new book X (a row of the table, with fields X.SeqNo and X.Pages), we compare X.Pages against the page count already stored inside each existing entry.
| Expression | For Y = [10, 350] | Meaning |
|---|---|---|
first(Y) | 10 | the SeqNo |
last(Y) | 350 | the number of pages |
3.2The procedure Insert(X, books)
Procedure Insert(X, books)
sBooks = []
inserted = False
foreach Y in books {
if (X.Pages <= last(Y) and not(inserted)) {
sBooks = sBooks ++ [[X.SeqNo, X.Pages]]
inserted = True
}
sBooks = sBooks ++ [Y]
}
if (not(inserted)) {
sBooks = sBooks ++ [[X.SeqNo, X.Pages]]
}
return(sBooks)
End Insert- The shape of the logic is identical to
SortedListInsert; a bare value has been swapped for a field of a record. X.Pages <= last(Y)asks "does the new book have fewer or equal pages than the book we are looking at?" The moment that is true, X is inserted right before Y.[[X.SeqNo, X.Pages]]has two pairs of brackets: the inner pair builds the record, the outer pair makes it a one-item list so that++can append it.- Here the two tests are joined with
andin oneif, instead of the nestedifs ofSortedListInsert. Both mean "not yet inserted, and this is the spot".
EndProcedureInsert and writes andnot(inserted); these notes use End Insert and and not(inserted), matching the other procedures.3.3Tracing an insert, end to end
Insert a book with SeqNo = 12, Pages = 350 into an already-sorted list.
| Step | books entry seen | Condition X.Pages <= last(Y) | Action |
|---|---|---|---|
| 1 | [5, 220] | 350 <= 220: false | copy [5, 220] |
| 2 | [10, 350] | 350 <= 350: true | insert [12, 350], then copy [10, 350] |
| 3 | [15, 350] | already inserted | copy [15, 350] |
| 4 | [20, 400] | already inserted | copy [20, 400] |
[5, 220], [12, 350], [10, 350], [15, 350], [20, 400]]. The new book lands right before the first existing book with an equal-or-greater page count, ahead of any ties. That is why the "not inserted" fallback at the end only ever runs when the new book has more pages than every book already in the list, or when the list started out empty.3.4<= here, < there
SortedListInsert | Insert | |
|---|---|---|
| Test | x < z | X.Pages <= last(Y) |
| A new item equal to existing ones goes | after them | in front of them |
| Inserting [12, 350] before [10, 350], [15, 350] | gives ..., [10, 350], [15, 350], [12, 350], ... | gives ..., [12, 350], [10, 350], [15, 350], ... |
<= the most recently inserted book comes first among books with the same number of pages.3.5Building the sorted library, one row at a time
Reading rows out of a table and inserting each one is exactly how a sorted list gets built from raw data:
books = []
while (Table 1 has more rows) {
Read top row X from Table 1
books = Insert(X, books)
Move X to Table 2
}Because every insert keeps the list sorted, once every row has been processed the first entry holds the fewest pages and the last entry holds the most: no separate sorting pass is needed. For example, if Table 1 holds the books in the order 5, 15, 10, 20, 12 (SeqNo, with the page counts above), books grows like this:
| Row read | books after the insert |
|---|---|
| [5, 220] | [[5, 220]] |
| [15, 350] | [[5, 220], [15, 350]] |
| [10, 350] | [[5, 220], [10, 350], [15, 350]] |
| [20, 400] | [[5, 220], [10, 350], [15, 350], [20, 400]] |
| [12, 350] | [[5, 220], [12, 350], [10, 350], [15, 350], [20, 400]] |
(This row order is an illustration chosen so that the list before the last insert matches the lecture's example; it was checked by running the pseudocode.)
3.6Going deeper
- This is insertion sort (extra). The loop above is
InsertionSortwritten over a table instead of a list: start empty, insert every item. - The first and the last (extra). After building,
first(books)is the shortest book andlast(books)the longest;last(last(books))is the largest page count. - Any field works. Sorting by another field only changes which value is compared; the pair (or record) is always carried along whole.
3.7Exam tips and common mistakes
- For a pair Y, write first(Y) and last(Y) next to it before tracing.
- Mark ties carefully: with <= the new item goes before them.
- Appending
[X.SeqNo, X.Pages]with single brackets: that appends two separate items, not one pair. - Comparing whole pairs instead of the page counts.
- Expecting a new book with equal pages to go after the existing ones.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
The book [8, 500] is inserted into [[5, 220], [10, 350], [15, 350], [20, 400]]. At which position (1 = first) does it land?
No book has 500 or more pages.
- The condition is false for every entry, so the fallback appends it.
- Answer: 5
Multiple Choice Question (MCQ): choose the one correct option.
Where does the book [3, 220] go when inserted into [[5, 220], [10, 350], [15, 350], [20, 400]]?
[5, 220][10, 350]The test is <=.
220 <= 220is true on the first entry, so it goes before[5, 220].- Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
Why does Insert append [[X.SeqNo, X.Pages]]?
++ joins two lists.
- The inner brackets make the pair, the outer brackets a one-item list holding that pair.
- Answer: option 3.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
last(Y) gives the page count of book Y<=, a new book goes in front of books with the same pagesCompare Insert with SortedListInsert.
- 1, 2 and 4 are true. Insert compares only the page counts (statement 3 is false).
- Answer: options 1, 2 and 4.
first(Y): SeqNo
last(Y): pages
and not(inserted)
Append [[SeqNo, Pages]]
Goes before [10, 350]
Ahead of ties
Insert every row
No separate sort
The Hypothesis and the Marks Lists
Making "does well" precise, extracting [SeqNo, marks] pairs and sorting them by marks.
The second half of the week uses sorting to answer a real question about student performance.
4.1The hypothesis we are testing
Here is the question: do students who do well in Maths also do at least as well in Physics? To check this against real data, the fuzzy idea has to become something a program can test, which means defining "does well" precisely.
- Give every student a grade in each subject: A, B, C or D.
- "Performs well in Maths" means a grade of B or above (A or B).
- "Performs at least as well in Physics" means the Physics grade is at least as high as the Maths grade: an A-in-Maths student needs an A in Physics too, but a B-in-Maths student is fine with an A or a B in Physics.
4.2The plan
- Assign grades to every student in both subjects, based on where their marks fall.
- Build separate lists of students who got an A or a B, in each subject: four lists in total.
- For every Maths-A student, check whether they are also in the Physics-A list.
- For every Maths-B student, check whether they are in the Physics-A or Physics-B list.
- Compare how many students confirmed the hypothesis against how many did not, to decide if it holds.
4.3Grading on a curve: quartiles
Rather than fixed mark cut-offs, grades here are assigned by position in the class: the top 25% of students get an A, the next 25% a B, then C, and the bottom 25% a D. To find those boundaries we need every student's marks as a sorted list. Each entry has to say whose mark it is, so we do not extract raw numbers: we extract pairs [StudentId, Marks].
4.4Extracting the marks lists
Procedure BuildMarksList(field)
marksList = []
while (Table 1 has more rows) {
Read the first row X in Table 1
marksList = marksList ++ [[X.SeqNo, X.field]]
Move X to Table 2
}
return(marksList)
End BuildMarksListfield is a placeholder for whichever subject we are pulling marks for, so the same procedure builds both lists:
mathsList = BuildMarksList(Mathematics)
physicsList = BuildMarksList(Physics)At this point we have two unsorted lists of [StudentId, Marks] pairs. The student id is the SeqNo field of the table.
4.5List operations we will lean on
| Operation | What it returns | On [1, 2, 3, 4] |
|---|---|---|
first(l) | the first element | 1 |
last(l) | the last element | 4 |
rest(l) | everything except the first element | [2, 3, 4] |
init(l) | everything except the last element | [1, 2, 3] |
On a pair p = [StudentId, Marks]: first(p) is the id and last(p) is the mark.
4.6Sorting the marks lists
The marks lists hold pairs, not plain numbers, so before reusing SortedListInsert the comparison is tweaked. We only ever want to compare the marks, never the student id, so instead of comparing whole pairs we compare last(x) against last(z).
Procedure SortedListInsert(l, x)
newList = []
inserted = False
foreach z in l {
if (not(inserted)) {
if (last(x) < last(z)) {
newList = newList ++ [x]
inserted = True
}
}
newList = newList ++ [z]
}
if (not(inserted)) {
newList = newList ++ [x]
}
return(newList)
End SortedListInsertInsertionSort itself does not change at all: it just calls whichever SortedListInsert is in scope, so plugging in this version is enough:
sortedMathsList = InsertionSort(mathsList)
sortedPhysicsList = InsertionSort(physicsList)With both lists sorted ascending by marks, position 0 is the lowest scorer and the last position is the top scorer: exactly what is needed to slice the class into quarters.
4.7A small class to follow along (illustrative)
The lecture uses the full Scores dataset. To follow every step by hand, Chapters 4 to 6 use these 12 illustrative students (not lecture data). All results below come from running the pseudocode.
| SeqNo | Mathematics | Physics |
|---|---|---|
| 0 | 92 | 88 |
| 1 | 45 | 60 |
| 2 | 78 | 91 |
| 3 | 66 | 52 |
| 4 | 85 | 70 |
| 5 | 58 | 75 |
| 6 | 71 | 64 |
| 7 | 88 | 95 |
| 8 | 39 | 41 |
| 9 | 80 | 83 |
| 10 | 62 | 58 |
| 11 | 50 | 47 |
sortedMathsList = [8, 39], [1, 45], [11, 50], [5, 58], [10, 62], [3, 66], [6, 71], [2, 78], [9, 80], [4, 85], [7, 88], [0, 92].
sortedPhysicsList = [8, 41], [11, 47], [3, 52], [10, 58], [1, 60], [6, 64], [4, 70], [5, 75], [9, 83], [0, 88], [2, 91], [7, 95].
4.8Exam tips and common mistakes
- Restate the hypothesis as rules before writing any code.
- For a pair, decide which of first and last is the key you compare.
- Comparing whole pairs (or ids) instead of
last(x)andlast(z). - Testing C and D students: the hypothesis is only about A and B in Maths.
- Reading position 0 as the top scorer: the list is ascending.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
Which student confirms the hypothesis?
A needs A; B needs A or B.
- Maths B with Physics A is "at least as well". The others either fall short or are not tested.
- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does BuildMarksList(Physics) return?
Each entry says whose mark it is.
- A list of
[X.SeqNo, X.Physics]pairs, in table order (not sorted). - Answer: option 3.
Numerical Answer Type (NAT).
For the illustrative class, what is last(last(sortedMathsList))?
The last pair is the top scorer; last of a pair is the mark.
last(sortedMathsList)=[0, 92], and its last element is 92.- Answer: 92
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about sorting the marks lists.
last(x) < last(z) compares marks, not idsWhat is compared, and what changes?
- 1, 2 and 4 are true. InsertionSort does not change (statement 3 is false).
- Answer: options 1, 2 and 4.
Physics at least as high
A needs A, B needs A or B
Four A/B lists
Check, then count
[SeqNo, marks] pairs
Unsorted
InsertionSort unchanged
Position 0: lowest
Assigning Grades by Quartile
SimpleGradeAssignment: grade by position in the sorted list, then unpack the four grade lists.
With the list sorted ascending by marks, splitting the class into quarters is just splitting the range of positions into four chunks: the bottom quarter of positions gets a D, the top quarter an A.
5.1The procedure SimpleGradeAssignment(l)
Procedure SimpleGradeAssignment(l)
classSize = length(l)
q4 = classSize / 4
q3 = classSize / 2
q2 = 3 * classSize / 4
gradeA = [], gradeB = [], gradeC = [], gradeD = []
position = 0
foreach x in l {
if (position > q2) {
gradeA = gradeA ++ [first(x)]
}
if (position > q3 and position <= q2) {
gradeB = gradeB ++ [first(x)]
}
if (position > q4 and position <= q3) {
gradeC = gradeC ++ [first(x)]
}
if (position <= q4) {
gradeD = gradeD ++ [first(x)]
}
position = position + 1
}
return([gradeA, gradeB, gradeC, gradeD])
End SimpleGradeAssignmentq4,q3,q2are the quarter, half and three-quarter marks of the class size. They are positions, not marks.positioncounts from 0 and goes up by 1 for each pair.- Each grade list stores
first(x), just the student id: once a grade is decided, we only need to know who it is. - The procedure returns one list holding four lists: [
gradeA,gradeB,gradeC,gradeD].
5.2Trace on 12 students
For 12 students: q4 = 12 / 4 = 3, q3 = 6, q2 = 9. The four tests sort the positions 0 to 11 like this:
| Grade | Test | Positions | Students |
|---|---|---|---|
| A | position > 9 | 10, 11 | 2 |
| B | 6 < position <= 9 | 7, 8, 9 | 3 |
| C | 3 < position <= 6 | 4, 5, 6 | 3 |
| D | position <= 3 | 0, 1, 2, 3 | 4 |
On the illustrative class: mathsGrades = [[7, 0], [2, 9, 4], [10, 3, 6], [8, 1, 11, 5]] and physicsGrades = [[2, 7], [5, 9, 0], [1, 6, 4], [8, 11, 3, 10]].
5.3The bands are not equal (extra)
Positions start at 0, but the tests use <= at each boundary. The position equal to q4 therefore goes to D, the one equal to q3 to C, and so on: every band takes one position from the band above it. When the class size is a multiple of 4, D gets one student too many and A one too few:
| Class size | q4, q3, q2 | A, B, C, D (lecture code) | Equal quarters |
|---|---|---|---|
| 8 | 2, 4, 6 | 1, 2, 2, 3 | 2, 2, 2, 2 |
| 12 | 3, 6, 9 | 2, 3, 3, 4 | 3, 3, 3, 3 |
| 20 | 5, 10, 15 | 4, 5, 5, 6 | 5, 5, 5, 5 |
| 30 | 7.5, 15, 22.5 | 7, 7, 8, 8 | 7 or 8 each |
Comparing with >= and < instead gives equal quarters whenever the class size is a multiple of 4:
if (position >= q2) {
gradeA = gradeA ++ [first(x)]
}
if (position >= q3 and position < q2) {
gradeB = gradeB ++ [first(x)]
}
if (position >= q4 and position < q3) {
gradeC = gradeC ++ [first(x)]
}
if (position < q4) {
gradeD = gradeD ++ [first(x)]
}5.4Unpacking the grade lists
Run SimpleGradeAssignment on both sorted lists, then unpack the returned list of four lists with first, rest, last and init, so each grade band can be used on its own:
mathsGrades = SimpleGradeAssignment(sortedMathsList)
physicsGrades = SimpleGradeAssignment(sortedPhysicsList)
mathsAGrades = first(mathsGrades)
mathsBGrades = first(rest(mathsGrades))
mathsCGrades = last(init(mathsGrades))
mathsDGrades = last(mathsGrades)
physicsAGrades = first(physicsGrades)
physicsBGrades = first(rest(physicsGrades))| Expression | Step by step | Result |
|---|---|---|
first(mathsGrades) | first of [A, B, C, D] | gradeA |
first(rest(mathsGrades)) | rest drops A: [B, C, D]; first of that | gradeB |
last(init(mathsGrades)) | init drops D: [A, B, C]; last of that | gradeC |
last(mathsGrades) | last of [A, B, C, D] | gradeD |
The same pattern applies for Physics. Only the A and B lists are needed for the test, so physicsCGrades and physicsDGrades are never unpacked.
5.5Going deeper
- Ties at a boundary (extra). Grades depend on position only, so two students with the same mark can get different grades if the boundary falls between them.
- Another way to reach gradeC (extra). Applying
resttwice and thenfirsttomathsGradesalso gives gradeC. - Why not store the marks? The test only asks "is this student in that list?", so ids are enough; storing pairs would make the comparison
x == ycompare marks too.
5.6Exam tips and common mistakes
- Compute q4, q3, q2 first, then list which positions each test accepts.
- Remember the list is ascending: the last positions are A.
- Assuming each band has exactly a quarter of the class.
- Mixing up
rest(drops the first) andinit(drops the last) when unpacking. - Storing whole pairs in the grade lists instead of
first(x).
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
With the lecture code and a class of 12 students, how many get an A?
A needs position > q2 = 9.
- Positions 10 and 11.
- Answer: 2
Numerical Answer Type (NAT).
With the lecture code and a class of 8 students, how many get a D?
q4 = 2 and D needs position <= 2.
- Positions 0, 1 and 2.
- Answer: 3
Numerical Answer Type (NAT).
With the lecture code and a class of 20 students, how many get an A?
q2 = 15.
- Positions 16, 17, 18 and 19.
- Answer: 4
Multiple Choice Question (MCQ): choose the one correct option.
Which expression gives gradeC from mathsGrades = [gradeA, gradeB, gradeC, gradeD]?
first(rest(mathsGrades))last(rest(mathsGrades))last(init(mathsGrades))first(init(mathsGrades))C is second from the end.
initdrops gradeD, and the last of what is left is gradeC.- Answer: option 3.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about SimpleGradeAssignment.
Look at what is stored and returned.
- 1, 2 and 3 are true. The bands are not always equal (statement 4 is false).
- Answer: options 1, 2 and 3.
q2 = 3n/4
Positions from 0
D: position <= q4
12 students: 2, 3, 3, 4
Ids via first(x)
last(init(...)), last
Testing the Hypothesis
Checking Maths A and B students against the Physics lists, with exitloop, and reaching a verdict.
With mathsAGrades, mathsBGrades, physicsAGrades and physicsBGrades ready, the last step checks each Maths A/B student against the matching Physics lists.
6.1Checking the A-grade students
For every Maths-A student, scan the Physics-A list looking for a match. exitloop breaks out of the inner foreach the moment a match is found, so we do not keep scanning after we already know the answer.
confirm = []
reject = []
foreach x in mathsAGrades {
found = False
foreach y in physicsAGrades {
if (x == y) {
confirm = confirm ++ [x]
found = True
exitloop
}
}
if (not(found)) {
reject = reject ++ [x]
}
}Every Maths-A student who also shows up in the Physics-A list is added to confirm; everyone else lands in reject. The found flag is reset to False for each student and tells the code after the inner loop whether a match was seen.
Immediately breaks out of the nearest enclosing foreach loop. Here that is the inner loop over physicsAGrades; the outer loop over mathsAGrades carries on with the next student.
6.2Checking the B-grade students
A Maths-B student satisfies the hypothesis with an A or a B in Physics, so this check first looks through the Physics-A list, and only searches Physics-B if no match turned up there.
foreach x in mathsBGrades {
found = False
foreach y in physicsAGrades {
if (x == y) {
confirm = confirm ++ [x]
found = True
exitloop
}
}
if (not(found)) {
foreach y in physicsBGrades {
if (x == y) {
confirm = confirm ++ [x]
found = True
exitloop
}
}
}
if (not(found)) {
reject = reject ++ [x]
}
}confirm and reject lists, which were set to [] only once, before the A check. Initialising them again before the B loop would throw away the A results.6.3Reaching a verdict
By the end, confirm holds every A/B-in-Maths student whose Physics grade backs up the hypothesis, and reject holds the rest. Comparing length(confirm) against length(confirm) + length(reject), the total number of A/B Maths students, tells us what fraction of students actually confirm the hypothesis.
6.4The whole test on the illustrative class
| List | Students |
|---|---|
mathsAGrades | 7, 0 |
mathsBGrades | 2, 9, 4 |
physicsAGrades | 2, 7 |
physicsBGrades | 5, 9, 0 |
| Student | Maths | Physics | Needed | Verdict |
|---|---|---|---|---|
| 7 | A (88) | A (95) | A | confirm |
| 0 | A (92) | B (88) | A | reject |
| 2 | B (78) | A (91) | A or B | confirm |
| 9 | B (80) | B (83) | A or B | confirm |
| 4 | B (85) | C (70) | A or B | reject |
So 60% of the students who did well in Maths did at least as well in Physics. Whether that is "enough" to accept the hypothesis is a judgement the lecture leaves open. With equal quarters (Chapter 5) the same class gives confirm = [7, 0, 2, 9] and reject = [4, 6], that is 4 of 6, about 67%.
6.5Going deeper
- Counting with exitloop (extra). For
mathsAGrades = [7, 0]andphysicsAGrades = [2, 7]: student 7 is compared with 2, then 7 (match, exit); student 0 with 2 and 7. That is 4 comparisons; withoutexitloopit would also be 4 here, but the saving grows with longer lists. - exitloop does not change the result here (extra). Ids are unique, so a student can match at most once in each Physics list.
exitloopsaves work;foundis what decides confirm or reject. - With member from Week 5 (extra). Each inner loop is a membership test, so the B check can be written as:
foreach x in mathsBGrades {
if (member(physicsAGrades, x) or member(physicsBGrades, x)) {
confirm = confirm ++ [x]
} else {
reject = reject ++ [x]
}
}- Not every student is tested. C and D students in Maths appear in neither list; the hypothesis says nothing about them.
- What a student with a high mark can teach (extra). Student 0 scored 88 in Physics and is still rejected: two classmates scored higher, and the lecture's bands give an A only to positions 10 and 11. The test is about ranks.
6.6Exam tips and common mistakes
- Write the four grade lists first, then go student by student.
- For a B student, check Physics-A first; look at Physics-B only if not found.
- Thinking
exitloopleaves both loops: it leaves only the nearestforeach. - Forgetting to reset
foundfor each student. - Dividing by the class size instead of
length(confirm)+length(reject). - Letting a Maths-A student pass with a Physics B.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
For the illustrative class, what is length(confirm) at the end?
Check the A students, then the B students.
- Student 7 (A, A), student 2 (B, A) and student 9 (B, B) confirm.
- Answer: 3
Multiple Choice Question (MCQ): choose the one correct option.
What does exitloop do inside the inner foreach y in physicsAGrades?
Nearest enclosing loop.
- It leaves only the inner loop; the outer loop goes on to the next student.
- Answer: option 2.
Numerical Answer Type (NAT).
With mathsAGrades = [7, 0] and physicsAGrades = [2, 7], how many times is x == y evaluated in the A check?
exitloop stops at a match.
- Student 7: 2, then 7 (match): 2 tests. Student 0: 2 and 7: 2 tests.
- Answer: 4
Multiple Choice Question (MCQ): choose the one correct option.
Which expression gives the fraction of A/B Maths students who confirm the hypothesis?
length(confirm) / (length(confirm) + length(reject))length(confirm) / length(reject)length(reject) / length(confirm)length(confirm) / 4Divide by everyone tested.
- Everyone tested is in exactly one of confirm and reject.
- Answer: option 1.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
Who is tested, and where can they end up?
- 1, 3 and 4 are true. A student is added to exactly one of confirm and reject (statement 2 is false).
- Answer: options 1, 3 and 4.
found flag per student
exitloop on a match
then Physics-B
else reject
Illustrative: 3 / 5
Boundaries change the verdict
Week 6 Summary Sheet
One page to revise all of Week 6: inserting and sorting, records, quartile grades and the hypothesis test.
The big picture
- Copy items until the first bigger one, insert, copy the rest: one pass.
- A flag adds x once; empty or largest: append.
- Insert every item into a growing sorted list.
- Invariant: sorted after every step.
- Compare one field (
last(Y)), carry the whole pair. <=puts a new item ahead of ties.
- A in Maths needs A in Physics; B needs A or B.
- Grades on a curve need sorted [id, marks] pairs.
- Bands by position at n/4, n/2, 3n/4.
- Returns four id lists; unpack with first, rest, last, init.
- Membership checks fill confirm and reject.
- Verdict: length(confirm) over everyone tested.
Patterns and how to use them
foreach z in l {
if (not(inserted)) {
if (x < z) {
newList = newList ++ [x]
inserted = True
}
}
newList = newList ++ [z]
}
if (not(inserted)) {
newList = newList ++ [x]
}Use whenA list is already sorted and one new value must go in without breaking the order.
- Copy items into
newListone by one. - At the first item bigger than x, add x first and set the flag.
- After the loop, append x if it was never inserted.
[10, 20, 30, 40] with 25 gives [10, 20, 25, 30, 40] after 3 tests.sortedList = []
foreach z in l {
sortedList = SortedListInsert(sortedList, z)
}Use whenYou need a whole list sorted.
- Start from the empty (sorted) list.
- Insert each item in turn.
- For descending order, compare with
x > z.
[30, 10, 40, 20]: [30], [10, 30], [10, 30, 40], [10, 20, 30, 40].if (last(x) < last(z)) {
newList = newList ++ [x]
inserted = True
}Use whenThe items are pairs or records and you sort by one field (pages, marks).
- Pick the field to compare (
lastof a pair). - Compare only that field; move the whole pair.
- Decide how ties go:
<after them,<=before them.
[12, 350] goes before [10, 350] when the test is <=.q4 = classSize / 4
q3 = classSize / 2
q2 = 3 * classSize / 4
if (position > q2) {
gradeA = gradeA ++ [first(x)]
}Use whenGrades are relative: top quarter A, next B, then C, bottom D.
- Sort [id, marks] pairs ascending.
- Compute q4, q3, q2 from the class size.
- Put each id in the band its position falls in; watch the
<=boundaries.
A = first(grades)
B = first(rest(grades))
C = last(init(grades))
D = last(grades)Use whenA procedure returns several lists packed into one.
- first and last reach the ends.
- rest drops the first, init drops the last.
- Combine them to reach the middle items.
[7, 0], [2, 9, 4], [10, 3, 6], [8, 1, 11, 5]]: B is [2, 9, 4], C is [10, 3, 6].found = False
foreach y in physicsAGrades {
if (x == y) {
confirm = confirm ++ [x]
found = True
exitloop
}
}
if (not(found)) {
reject = reject ++ [x]
}Use whenYou only need to know whether an item is in a list, and what to do if it is not.
- Reset
foundfor each item. - On a match, record it, set the flag and
exitloop. - After the loop, use the flag for the "not found" case.
confirm = [7, 2, 9], reject = [0, 4], verdict 3 / 5.Glossary: list operations
| Operation | Meaning |
|---|---|
first(l) | The first element of l. |
last(l) | The last element of l. |
rest(l) | All of l except the first element. |
init(l) | All of l except the last element. |
length(l) | The number of elements in l. |
l1 ++ l2 | Appends list l2 onto the end of list l1. |
exitloop | Immediately breaks out of the nearest enclosing foreach loop. |
The procedures of this week
| Procedure | Takes | Returns |
|---|---|---|
SortedListInsert | a sorted list l, a value x | l with x in its place |
InsertionSort | a list l | l sorted ascending |
Insert | a row X, a sorted list of books | books with [X.SeqNo, X.Pages] in place |
BuildMarksList | a field name | [SeqNo, mark] pairs |
SimpleGradeAssignment | pairs sorted by marks | [gradeA, gradeB, gradeC, gradeD] |
The big ideas, in one line each
- Inserting into a sorted list takes one pass: copy until the new item's place, insert, copy the rest.
- Insertion sort builds a sorted list by inserting each item into a fresh list, one at a time.
- The same insert logic works on records: compare one field instead of a bare value.
- Sorting turns a fuzzy question into a precise one: once marks are sorted, quartile boundaries are just positions.
- Testing a hypothesis with lists comes down to building the right lists, then checking membership across them.
Common mistakes
- Copy z on every pass, outside the
if; the finalifappends x when it was never inserted.
- This insertion sort needs ½ × N × (N − 1) tests on an already sorted list.
++ [[SeqNo, Pages]]appends one pair;++ [SeqNo, Pages]appends two items.
- Compare
last(x)andlast(z), the marks, not the ids.
- With positions from 0 and
<=, the lecture's bands are uneven (12 students: 2, 3, 3, 4).
- It leaves only the nearest
foreach, not every loop.