SECTION 19 / 28

Tutorial: trace the numbered book-insertion code

1 min read
The tutorial inserts [12,350] before the existing 350-page books because its comparison uses ≤.
The tutorial inserts [12,350] before the existing 350-page books because its comparison uses ≤.
REAL COURSE DATA · SORT, GROUP AND VERIFY

Tutorial: insert a book and inspect line execution

Follow the selected procedure. Change a field, tie rule or weekday and explain why the result changes.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next change. Keep track of which list level, field and position convention the procedure uses.

1  Procedure Insert(X, books)
2      sBooks = []
3      inserted = false
4      foreach Y in books:
5          if X.Pages <= last(Y) AND NOT inserted:
6              sBooks = sBooks ++ [[X.SeqNo,X.Pages]]
7              inserted = true
9          sBooks = sBooks ++ [Y]
11     if NOT inserted:
12         sBooks = sBooks ++ [[X.SeqNo,X.Pages]]
14     return sBooks
15 End Procedure

The exercise describes a library table of 1,000 books, but the concrete insertion example supplies four pairs: [[5,220],[10,350],[15,350],[20,400]]. We trace those given pairs and an empty case without inventing 1,000 book records.

For empty books, line 4 has no body executions. Among the tutorial’s offered body-line choices, only line 12 executes. Initialization, the final test and return also occur; “only line 12” refers to the options in that multiple-select question, not every line of the procedure.

For X.SeqNo = 12 and X.Pages = 350, the result is [[5,220],[12,350],[10,350],[15,350],[20,400]]. Copy line 9 executes for every old Y, including after the insertion. Empty input and an item larger than all page counts use line 12.

Try it yourself

Does line 5 execute inside foreach on empty input?

Show explained answer

No. There is no Y to process, so the entire loop body is skipped.

Try it yourself

Why is the new 350-page book second rather than fourth?

Show explained answer

The ≤ test passes at the first old 350-page book, so the new pair is inserted before old equals.

Try it yourself

Does the sorted input get mutated by this function’s code?

Show explained answer

It builds sBooks and returns it. The caller assigns that result if it wants its books variable updated.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑