Weeks
Computational ThinkingWeek 6 · Sorting Lists and Testing a Hypothesis
Week 6 Notes

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.

7 chapters28 worked examples~37 min read
Sorted insertInsertion sortRecordsQuartilesHypothesis testing

Chapters

  1. 01Inserting into a Sorted ListSorting lists
  2. 02Insertion SortSorting lists
  3. 03Inserting Records: the Library ExampleSorting lists
  4. 04The Hypothesis and the Marks ListsCorrelating performance
  5. 05Assigning Grades by QuartileCorrelating performance
  6. 06Testing the HypothesisCorrelating performance
  7. 07Week 6 Summary SheetAll topics
01
Sorting lists

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.

l (sorted)10203040x = 25newList102025304025 < 30: first bigger item, insert x here
Figure 1. Inserting 25 into [10, 20, 30, 40]: copy, insert in front of 30, copy the rest

1.3The procedure SortedListInsert(l, x)

SortedListInsert.pseudo
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 SortedListInsert
  • newList is built from scratch; the original l is 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 inserted flag makes sure x is only ever added once, even though the loop keeps running afterwards.
Key idea

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)

Passzinserted beforeTest x < zWhat happensnewList after
110False25 < 10: Falsecopy 10[10]
220False25 < 20: Falsecopy 20[10, 20]
330False25 < 30: Trueinsert 25, copy 30[10, 20, 25, 30]
440Truenot checkedcopy 40[10, 20, 25, 30, 40]
afterTruefinal 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

l is emptyl[]x=7[7]appendedx smaller than alll[1020]x=5[51020]at the frontx larger than alll[1020]x=50[102050]at the end
Figure 2. The three boundary cases
CaseWhat happens in the loopWhere x ends up
l is emptythe loop body never runsappended by the final if
x is smaller than everything in lx < z is True on the first itemright at the front
x is larger than everything in lx < z is never Trueappended at the end by the final if
Ties (extra). The test is strict (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 < z tests is the position where x lands, plus one, unless x goes at the end, in which case it is length(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

Exam tips
  • 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.
Common mistakes
  • Putting newList = newList ++ [z] inside the else: 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 < z is tested on every pass; after insertion it is skipped.

Practice questions (graded-assignment style)

Q1Where does 25 go?

Multiple Choice Question (MCQ): choose the one correct option.

Let l = [10, 20, 30, 40]. What does SortedListInsert(l, 25) return?

1
[10, 20, 30, 40, 25]
2
[10, 20, 25, 30, 40]
3
[25, 10, 20, 30, 40]
4
[10, 25, 20, 30, 40]
Solution
Idea

x goes in front of the first bigger item.

  • The first item bigger than 25 is 30.
  • Answer: option 2.
Q2Counting tests

Numerical Answer Type (NAT).

With l = [10, 20, 30, 40], how many times is x < z evaluated in SortedListInsert(l, 25)?

Solution
Idea

After insertion the test is skipped.

  • Tested against 10, 20 and 30; on 40 inserted is already True.
  • Answer: 3
Q3The largest value

Numerical Answer Type (NAT).

With l = [10, 20, 30, 40], how many times is x < z evaluated in SortedListInsert(l, 50)?

Solution
Idea

No item is bigger than 50.

  • The test is False on all four items, and 50 is appended by the final if.
  • Answer: 4
Q4An equal value

Multiple Choice Question (MCQ): choose the one correct option.

With l = [10, 20, 30], where does the new 20 go in SortedListInsert(l, 20)?

1
At the front
2
In front of the old 20
3
Just after the old 20
4
At the end
Solution
Idea

The test is strict.

  • 20 < 20 is False, so the old 20 is copied first; 20 < 30 is True, so the new 20 goes in front of 30.
  • Answer: option 3.
Q5The procedure

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements about SortedListInsert.

1
The inserted flag makes sure x is added only once
2
The result has one more item than l
3
The final if runs only when l is empty
4
Every item of l is copied exactly once
Solution
Idea

Think about the flag and the final if.

  • 1, 2 and 4 are true. The final if also runs when x is larger than every item (statement 3 is false).
  • Answer: options 1, 2 and 4.
Revision overview
Why sortTop values at one end
Duplicates side by side
Bands by position
The ideaCopy items one by one
Stop at the first bigger item
Insert, then copy the rest
The flaginserted starts False
x added only once
Test skipped afterwards
Sorted insertSortedListInsert
Trace[10, 20, 30, 40] with 25
3 tests
[10, 20, 25, 30, 40]
BoundariesEmpty l: append
Smallest: front
Largest: end
TiesStrict x < z
New equal value goes after
Matters for records
Revision: putting one value into a sorted list in one pass
Next · Sorting listsInsertion Sort
02
Sorting lists

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.

InsertionSort.pseudo
Procedure InsertionSort(l)
  sortedList = []
  foreach z in l {
    sortedList = SortedListInsert(sortedList, z)
  }
  return(sortedList)
End InsertionSort

2.2Trace: InsertionSort([30, 10, 40, 20])

item zsortedList after inserting zstart[]30[30]10[1030]40[103040]20[10203040]
Figure 3. sortedList after each insert; the newly inserted item is highlighted
zWhere it goessortedList after
30empty list: appended[30]
10in front of 30[10, 30]
40larger than all: appended[10, 30, 40]
20in front of 30[10, 20, 30, 40]

2.3Why this works: the invariant

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:

descending.pseudo
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 insertTotal tests of x < z
[1, 2, 3, 4, 5, 6] (already sorted)0, 1, 2, 3, 4, 515 = ½ × 6 × 5
[6, 5, 4, 3, 2, 1] (reverse sorted)0, 1, 1, 1, 1, 15
[30, 10, 40, 20] (4 items)0, 1, 2, 25
A surprise. This version scans from the front, so an already sorted input is its worst case: every new item is the largest so far and is compared with everything, giving ½ × 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 < z is 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. InsertionSort only calls SortedListInsert. 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 l is not changed; the sorted version is a new list.

2.8Exam tips and common mistakes

Exam tips
  • Write sortedList after every insert; one line per item of the input.
  • To count tests, count for each insert separately and add them up.
Common mistakes
  • Forgetting that sortedList starts as [], not as the first item.
  • Assuming a sorted input is the easy case for this version.
  • Changing x < z to x > z and still expecting ascending order.

Practice questions (graded-assignment style)

Q1Midway

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?

1
[10, 30, 40]
2
[30, 10, 40]
3
[10, 20, 30]
4
[10, 20, 30, 40]
Solution
Idea

Insert 30, then 10, then 40.

  • [30], then [10, 30], then [10, 30, 40].
  • Answer: option 1.
Q2Sorted input

Numerical Answer Type (NAT).

Let l = [1, 2, 3, 4, 5, 6]. How many times is x < z evaluated by InsertionSort(l)?

Solution
Idea

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
Q3Reverse input

Numerical Answer Type (NAT).

Let l = [6, 5, 4, 3, 2, 1]. How many times is x < z evaluated by InsertionSort(l)?

Solution
Idea

Each new item is smaller than the first item.

  • The first insert makes 0 tests; each of the other five makes 1.
  • Answer: 5
Q4Descending

Multiple Choice Question (MCQ): choose the one correct option.

Which change to SortedListInsert makes InsertionSort sort in descending order?

1
Start sortedList as [0]
2
Replace x < z by x > z
3
Use z ++ x
4
Remove the inserted flag
Solution
Idea

x should go in front of the first smaller item.

  • Replace x < z by x > z; nothing else changes.
  • Answer: option 2.
Q5The invariant

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements about InsertionSort.

1
An empty list is sorted
2
sortedList is sorted after every pass of the loop
3
It calls SortedListInsert once per item
4
It rearranges the items of l in place
Solution
Idea

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.
Revision overview
The proceduresortedList = []
Insert every item
Return sortedList
Trace30, 10, 40, 20
[30] → [10, 30]
→ [10, 20, 30, 40]
Insertion sortInsertionSort
Invariant[] is sorted
Each insert keeps it sorted
So the end is sorted
Variationsx > z: descending
Compare a field: records
Sorted input: ½ × N × (N − 1) tests
Revision: sorting by repeated insertion, and why it is correct
Next · Sorting listsInserting Records: the Library Example
03
Sorting lists

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.

ExpressionFor Y = [10, 350]Meaning
first(Y)10the SeqNo
last(Y)350the number of pages

3.2The procedure Insert(X, books)

Insert.pseudo
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 and in one if, instead of the nested ifs of SortedListInsert. Both mean "not yet inserted, and this is the spot".
Spelling on the slide. The PDF ends this procedure with 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.

books (sorted by pages)new book X = [12, 350][5, 220]350 <= 220: false[10, 350]350 <= 350: true[15, 350]already inserted[20, 400]already insertedsBooks[5, 220][12, 350][10, 350][15, 350][20, 400]
Figure 4. The new book goes in front of the first book with as many or more pages
Stepbooks entry seenCondition X.Pages <= last(Y)Action
1[5, 220]350 <= 220: falsecopy [5, 220]
2[10, 350]350 <= 350: trueinsert [12, 350], then copy [10, 350]
3[15, 350]already insertedcopy [15, 350]
4[20, 400]already insertedcopy [20, 400]
Result[[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

SortedListInsertInsert
Testx < zX.Pages <= last(Y)
A new item equal to existing ones goesafter themin 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], ...
Why it matters (extra). Both orders are sorted by pages, so either is correct for the lecture's purpose. The difference only shows among ties: with <= 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:

build-library.pseudo
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 readbooks 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 InsertionSort written 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 and last(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

Exam tips
  • 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.
Common mistakes
  • 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)

Q1A long book

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?

Solution
Idea

No book has 500 or more pages.

  • The condition is false for every entry, so the fallback appends it.
  • Answer: 5
Q2A tie at the start

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]]?

1
First
2
Second, after [5, 220]
3
Before [10, 350]
4
Last
Solution
Idea

The test is <=.

  • 220 <= 220 is true on the first entry, so it goes before [5, 220].
  • Answer: option 1.
Q3Double brackets

Multiple Choice Question (MCQ): choose the one correct option.

Why does Insert append [[X.SeqNo, X.Pages]]?

1
It sorts the pair
2
It appends SeqNo and Pages as two items
3
It appends one pair as a single item
4
It is a typing error
Solution
Idea

++ joins two lists.

  • The inner brackets make the pair, the outer brackets a one-item list holding that pair.
  • Answer: option 3.
Q4Records

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
last(Y) gives the page count of book Y
2
With <=, a new book goes in front of books with the same pages
3
Insert compares whole pairs
4
Inserting every row of the table builds a sorted list
Solution
Idea

Compare 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.
Revision overview
Records[SeqNo, Pages]
first(Y): SeqNo
last(Y): pages
Insert(X, books)X.Pages <= last(Y)
and not(inserted)
Append [[SeqNo, Pages]]
LibraryInsert
TraceInsert [12, 350]
Goes before [10, 350]
Ahead of ties
Buildbooks = []
Insert every row
No separate sort
Revision: the insertion idea on records, compared by one field
Next · Correlating performanceThe Hypothesis and the Marks Lists
04
Correlating performance

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.

Turning the question into rules
  • 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.
Maths gradePhysics grade neededAAconfirms the hypothesisBABCnot testedDnot tested
Figure 5. The Physics grade each Maths grade needs; C and D students are not part of the test

4.2The plan

  1. Assign grades to every student in both subjects, based on where their marks fall.
  2. Build separate lists of students who got an A or a B, in each subject: four lists in total.
  3. For every Maths-A student, check whether they are also in the Physics-A list.
  4. For every Maths-B student, check whether they are in the Physics-A or Physics-B list.
  5. Compare how many students confirmed the hypothesis against how many did not, to decide if it holds.
Table 1pairsBuildMarksListsortedInsertionSort4 listsSimpleGradeAssignmentA, B listsfirst, rest,last, initnestedforeachconfirm / reject
Figure 6. From the table to confirm and reject, one procedure per step

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

Relative grades (extra). A grade on a curve depends on the rest of the class. A student with 88 in Physics can get a B if enough classmates scored higher. The hypothesis is therefore about rank in each subject, not about raw marks.

4.4Extracting the marks lists

BuildMarksList.pseudo
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 BuildMarksList

field is a placeholder for whichever subject we are pulling marks for, so the same procedure builds both lists:

build-calls.pseudo
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.

Table 1 is scanned twice (extra). Each call moves every row from Table 1 to Table 2. The second call only works if Table 1 has been restored first, the same side-effect point as in Weeks 3 and 5.

4.5List operations we will lean on

OperationWhat it returnsOn [1, 2, 3, 4]
first(l)the first element1
last(l)the last element4
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).

SortedListInsert-pairs.pseudo
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 SortedListInsert

InsertionSort itself does not change at all: it just calls whichever SortedListInsert is in scope, so plugging in this version is enough:

sort-calls.pseudo
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.

SeqNoMathematicsPhysics
09288
14560
27891
36652
48570
55875
67164
78895
83941
98083
106258
115047

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

Exam tips
  • Restate the hypothesis as rules before writing any code.
  • For a pair, decide which of first and last is the key you compare.
Common mistakes
  • Comparing whole pairs (or ids) instead of last(x) and last(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)

Q1Who confirms?

Multiple Choice Question (MCQ): choose the one correct option.

Which student confirms the hypothesis?

1
Maths A, Physics B
2
Maths B, Physics A
3
Maths B, Physics C
4
Maths C, Physics A
Solution
Idea

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

Multiple Choice Question (MCQ): choose the one correct option.

What does BuildMarksList(Physics) return?

1
The Physics marks, sorted
2
The top quarter of Physics marks
3
A list of [SeqNo, Physics mark] pairs
4
One [SeqNo, Physics mark] pair
Solution
Idea

Each entry says whose mark it is.

  • A list of [X.SeqNo, X.Physics] pairs, in table order (not sorted).
  • Answer: option 3.
Q3Top mark

Numerical Answer Type (NAT).

For the illustrative class, what is last(last(sortedMathsList))?

Solution
Idea

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
Q4The comparison

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements about sorting the marks lists.

1
last(x) < last(z) compares marks, not ids
2
Position 0 holds the lowest mark after sorting
3
InsertionSort must be rewritten for pairs
4
The pairs are kept whole while sorting
Solution
Idea

What 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.
Revision overview
HypothesisGood in Maths: A or B
Physics at least as high
A needs A, B needs A or B
PlanGrade both subjects
Four A/B lists
Check, then count
Maths vs PhysicsCorrelating performance
Marks listsBuildMarksList(field)
[SeqNo, marks] pairs
Unsorted
Sorting pairslast(x) < last(z)
InsertionSort unchanged
Position 0: lowest
Revision: turning the question into rules, and preparing sorted marks lists
Next · Correlating performanceAssigning Grades by Quartile
05
Correlating performance

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)

SimpleGradeAssignment.pseudo
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 SimpleGradeAssignment
  • q4, q3, q2 are the quarter, half and three-quarter marks of the class size. They are positions, not marks.
  • position counts 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:

GradeTestPositionsStudents
Aposition > 910, 112
B6 < position <= 97, 8, 93
C3 < position <= 64, 5, 63
Dposition <= 30, 1, 2, 34

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)

position01234567891011lecture code (12 students)DDDDCCCBBBAAequal quartersDDDCCCBBBAAAq4 = 3q3 = 6q2 = 9
Figure 7. Bands by position for 12 students: the lecture code (top) and equal quarters (bottom)

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 sizeq4, q3, q2A, B, C, D (lecture code)Equal quarters
82, 4, 61, 2, 2, 32, 2, 2, 2
123, 6, 92, 3, 3, 43, 3, 3, 3
205, 10, 154, 5, 5, 65, 5, 5, 5
307.5, 15, 22.57, 7, 8, 87 or 8 each

Comparing with >= and < instead gives equal quarters whenever the class size is a multiple of 4:

equal-quarters.pseudo
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)]
}
Does it change the answer? Yes, it can. On the illustrative class the lecture code gives a verdict of 3 out of 5 students; equal quarters give 4 out of 6 (Chapter 6). The slide calls this a "simple" grade assignment; how the boundaries are drawn is a real choice in the analysis. (This check is an extra; all counts come from running both versions.)

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:

unpack.pseudo
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))
mathsGrades= [gradeAfirst(…)gradeBfirst(rest(…))gradeClast(init(…))gradeDlast(…)]
Figure 8. Getting each grade list out of [gradeA, gradeB, gradeC, gradeD]
ExpressionStep by stepResult
first(mathsGrades)first of [A, B, C, D]gradeA
first(rest(mathsGrades))rest drops A: [B, C, D]; first of thatgradeB
last(init(mathsGrades))init drops D: [A, B, C]; last of thatgradeC
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 rest twice and then first to mathsGrades also 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 == y compare marks too.

5.6Exam tips and common mistakes

Exam tips
  • Compute q4, q3, q2 first, then list which positions each test accepts.
  • Remember the list is ascending: the last positions are A.
Common mistakes
  • Assuming each band has exactly a quarter of the class.
  • Mixing up rest (drops the first) and init (drops the last) when unpacking.
  • Storing whole pairs in the grade lists instead of first(x).

Practice questions (graded-assignment style)

Q1A grades for 12

Numerical Answer Type (NAT).

With the lecture code and a class of 12 students, how many get an A?

Solution
Idea

A needs position > q2 = 9.

  • Positions 10 and 11.
  • Answer: 2
Q2D grades for 8

Numerical Answer Type (NAT).

With the lecture code and a class of 8 students, how many get a D?

Solution
Idea

q4 = 2 and D needs position <= 2.

  • Positions 0, 1 and 2.
  • Answer: 3
Q3A grades for 20

Numerical Answer Type (NAT).

With the lecture code and a class of 20 students, how many get an A?

Solution
Idea

q2 = 15.

  • Positions 16, 17, 18 and 19.
  • Answer: 4
Q4Unpacking

Multiple Choice Question (MCQ): choose the one correct option.

Which expression gives gradeC from mathsGrades = [gradeA, gradeB, gradeC, gradeD]?

1
first(rest(mathsGrades))
2
last(rest(mathsGrades))
3
last(init(mathsGrades))
4
first(init(mathsGrades))
Solution
Idea

C is second from the end.

  • init drops gradeD, and the last of what is left is gradeC.
  • Answer: option 3.
Q5The procedure

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements about SimpleGradeAssignment.

1
It stores student ids, not marks
2
It returns a list of four lists
3
It expects the list sorted ascending by marks
4
Each grade always gets exactly a quarter of the class
Solution
Idea

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.
Revision overview
Boundariesq4 = n/4, q3 = n/2
q2 = 3n/4
Positions from 0
BandsA: position > q2
D: position <= q4
12 students: 2, 3, 3, 4
GradesSimpleGradeAssignment
Output[gradeA, gradeB, gradeC, gradeD]
Ids via first(x)
Unpackingfirst, first(rest(...))
last(init(...)), last
Revision: grading by position in a sorted list and unpacking the result
Next · Correlating performanceTesting the Hypothesis
06
Correlating performance

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.

check-A.pseudo
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.

exitloop

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.

check-B.pseudo
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]
  }
}
Maths-B student xx in physicsAGrades?yesconfirmnox in physicsBGrades?yesnorejectexitloop on a match
Figure 9. How one Maths-B student is checked
One confirm, one reject. Both loops add to the same 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.

fraction confirmed=length(confirm)length(confirm)+length(reject)\text{fraction confirmed} = \frac{\text{length(confirm)}}{\text{length(confirm)} + \text{length(reject)}}

6.4The whole test on the illustrative class

ListStudents
mathsAGrades7, 0
mathsBGrades2, 9, 4
physicsAGrades2, 7
physicsBGrades5, 9, 0
StudentMathsPhysicsNeededVerdict
7A (88)A (95)Aconfirm
0A (92)B (88)Areject
2B (78)A (91)A or Bconfirm
9B (80)B (83)A or Bconfirm
4B (85)C (70)A or Breject
confirm[729]reject[04]fraction confirmed3 / (3 + 2) = 0.6
Figure 10. confirm = [7, 2, 9], reject = [0, 4]: 3 of 5 confirm

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] and physicsAGrades = [2, 7]: student 7 is compared with 2, then 7 (match, exit); student 0 with 2 and 7. That is 4 comparisons; without exitloop it 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. exitloop saves work; found is 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:
check-B-with-member.pseudo
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

Exam tips
  • 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.
Common mistakes
  • Thinking exitloop leaves both loops: it leaves only the nearest foreach.
  • Forgetting to reset found for 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)

Q1Confirmed

Numerical Answer Type (NAT).

For the illustrative class, what is length(confirm) at the end?

Solution
Idea

Check the A students, then the B students.

  • Student 7 (A, A), student 2 (B, A) and student 9 (B, B) confirm.
  • Answer: 3
Q2exitloop

Multiple Choice Question (MCQ): choose the one correct option.

What does exitloop do inside the inner foreach y in physicsAGrades?

1
Ends both loops
2
Ends the inner loop only
3
Skips to the next y
4
Ends the whole procedure
Solution
Idea

Nearest enclosing loop.

  • It leaves only the inner loop; the outer loop goes on to the next student.
  • Answer: option 2.
Q3Comparisons

Numerical Answer Type (NAT).

With mathsAGrades = [7, 0] and physicsAGrades = [2, 7], how many times is x == y evaluated in the A check?

Solution
Idea

exitloop stops at a match.

  • Student 7: 2, then 7 (match): 2 tests. Student 0: 2 and 7: 2 tests.
  • Answer: 4
Q4The verdict

Multiple Choice Question (MCQ): choose the one correct option.

Which expression gives the fraction of A/B Maths students who confirm the hypothesis?

1
length(confirm) / (length(confirm) + length(reject))
2
length(confirm) / length(reject)
3
length(reject) / length(confirm)
4
length(confirm) / 4
Solution
Idea

Divide by everyone tested.

  • Everyone tested is in exactly one of confirm and reject.
  • Answer: option 1.
Q5The test

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
A Maths-C student is in neither confirm nor reject
2
A student can be in both confirm and reject
3
The B check searches Physics-B only if the student was not found in Physics-A
4
With unique ids, removing exitloop would not change confirm
Solution
Idea

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.
Revision overview
A checkMaths-A in Physics-A?
found flag per student
exitloop on a match
B checkPhysics-A first
then Physics-B
else reject
Testingconfirm / reject
Verdictlength(confirm) / total tested
Illustrative: 3 / 5
NotesRanks, not marks
Boundaries change the verdict
Revision: checking membership across grade lists and reaching a verdict
Next · All topicsWeek 6 Summary Sheet
07
All topics

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

Sorted insert
  • Copy items until the first bigger one, insert, copy the rest: one pass.
  • A flag adds x once; empty or largest: append.
Insertion sort
  • Insert every item into a growing sorted list.
  • Invariant: sorted after every step.
Records
  • Compare one field (last(Y)), carry the whole pair.
  • <= puts a new item ahead of ties.
Hypothesis
  • A in Maths needs A in Physics; B needs A or B.
  • Grades on a curve need sorted [id, marks] pairs.
Quartile grades
  • Bands by position at n/4, n/2, 3n/4.
  • Returns four id lists; unpack with first, rest, last, init.
Testing
  • Membership checks fill confirm and reject.
  • Verdict: length(confirm) over everyone tested.

Patterns and how to use them

Insert into a sorted list
One pass with a flag
pseudocode
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.

  1. Copy items into newList one by one.
  2. At the first item bigger than x, add x first and set the flag.
  3. After the loop, append x if it was never inserted.
Example[10, 20, 30, 40] with 25 gives [10, 20, 25, 30, 40] after 3 tests.
Insertion sort
Repeat the insert
pseudocode
sortedList = []
foreach z in l {
  sortedList = SortedListInsert(sortedList, z)
}

Use whenYou need a whole list sorted.

  1. Start from the empty (sorted) list.
  2. Insert each item in turn.
  3. For descending order, compare with x > z.
Example[30, 10, 40, 20]: [30], [10, 30], [10, 30, 40], [10, 20, 30, 40].
Sort records by one field
Compare the key only
pseudocode
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).

  1. Pick the field to compare (last of a pair).
  2. Compare only that field; move the whole pair.
  3. Decide how ties go: < after them, <= before them.
ExampleBooks sorted by pages: [12, 350] goes before [10, 350] when the test is <=.
Grades by position
Bands from the sorted list
pseudocode
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.

  1. Sort [id, marks] pairs ascending.
  2. Compute q4, q3, q2 from the class size.
  3. Put each id in the band its position falls in; watch the <= boundaries.
Example12 students: q4 = 3, q3 = 6, q2 = 9. The lecture code gives A 2, B 3, C 3, D 4.
Unpack a list of lists
Four grade lists
pseudocode
A = first(grades)
B = first(rest(grades))
C = last(init(grades))
D = last(grades)

Use whenA procedure returns several lists packed into one.

  1. first and last reach the ends.
  2. rest drops the first, init drops the last.
  3. Combine them to reach the middle items.
Example[[7, 0], [2, 9, 4], [10, 3, 6], [8, 1, 11, 5]]: B is [2, 9, 4], C is [10, 3, 6].
Search with exitloop
Stop at the first match
pseudocode
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.

  1. Reset found for each item.
  2. On a match, record it, set the flag and exitloop.
  3. After the loop, use the flag for the "not found" case.
ExampleIllustrative class: confirm = [7, 2, 9], reject = [0, 4], verdict 3 / 5.

Glossary: list operations

OperationMeaning
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 ++ l2Appends list l2 onto the end of list l1.
exitloopImmediately breaks out of the nearest enclosing foreach loop.

The procedures of this week

ProcedureTakesReturns
SortedListInserta sorted list l, a value xl with x in its place
InsertionSorta list ll sorted ascending
Inserta row X, a sorted list of booksbooks with [X.SeqNo, X.Pages] in place
BuildMarksLista field name[SeqNo, mark] pairs
SimpleGradeAssignmentpairs 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

Losing an item on insert
  • Copy z on every pass, outside the if; the final if appends x when it was never inserted.
Sorted input is not easy
  • This insertion sort needs ½ × N × (N − 1) tests on an already sorted list.
Single brackets for a pair
  • ++ [[SeqNo, Pages]] appends one pair; ++ [SeqNo, Pages] appends two items.
Comparing whole pairs
  • Compare last(x) and last(z), the marks, not the ids.
Equal quarters
  • With positions from 0 and <=, the lecture's bands are uneven (12 students: 2, 3, 3, 4).
exitloop
  • It leaves only the nearest foreach, not every loop.
Back to top