ICS3U Computer Science • Ontario Grade 11

Revision sheet: array algorithms (ICS3U)

This sheet is not a summary of the array algorithms chapter of ICS3U, Introduction to Computer Science, Grade 11: you already have your notes.

What the sheet covers

It answers one question only, what makes students lose marks when they count, total, find the largest value, search, insert into a sorted array or delete from the middle of an array, and which precise gesture avoids each loss.

Most of these mistakes give no error message: a maximum started at 0 prints 0, a search prints Not found for a value that is there, a deletion prints the last value twice. The program runs, and it takes a trace, or a well-chosen test, to show the mistake. The code is in Python 3, without max(), sum(), in, insert() or pop() in the answers, and every value on this sheet comes from a program that was run.

  • 9 mistakes that cost marks
  • 5 figures
  • 15 min reading
Do the chapter's exercises

The thread of the chapter

An array algorithm is one traversal plus a few variables that remember what it has seen: they start from a value that is right before the first pass, the conclusion comes after the loop, and a shift always copies into a cell whose value has already moved.

Topics covered

  • Counting algorithm
  • Running total
  • Average of an array
  • Array maximum and minimum
  • Linear search
  • Number of comparisons
  • Sorted array
  • Partially filled array
  • Insertion by shifting
  • Deletion by shifting
  • Trace table
  • Empty array

The essentials

One traversal, variables that remember

  • • Count: count = 0 before the loop, count = count + 1 when the test is true. Total: total = 0, total = total + a[i] at each pass.
  • • Average: total / len(a), after the loop, and only if len(a) > 0: an empty array has no average.
  • • Largest value: largest = a[0] and where = 0, then for i in range(1, len(a)): if a[i] > largest:. The start is a real element, so it is right before the first pass.
  • • Linear search: pos = -1, then while i < len(a) and pos == -1: compare a[i] with the target. -1 means not found, and it is decided after the loop.
  • • Number of comparisons of one run: a target found first at index k costs k + 1, an absent target costs len(a).
ia[i]largest = 0largest = a[0]0-60-61-20-22-80-23-20-24-50-2a = [-6, -2, -8, -2, -5]: largest after each pass
On negative values, largest = 0 is never beaten and the answer stays 0, which is not in a; largest = a[0] ends at -2, the right answer.

A partially filled array, and shifts

  • • A Java array has a fixed number of cells: the program keeps spare cells at the end and a variable size, the number of cells in use, indices 0 to size - 1. The Python list of an ICS3U answer works the same way.
  • • Insertion into a sorted array: i = size - 1, while i >= 0 and a[i] > value: a[i + 1] = a[i] and i = i - 1; then a[i + 1] = value and size = size + 1.
  • • Deletion at index pos: for i in range(pos, size - 1): a[i] = a[i + 1]; then size = size - 1.
  • • The direction follows the gap: an insertion opens a gap on the left, so the shifts start from the right; a deletion fills a gap on the left, so they start from it.
  • • Before an insertion, check size < len(a); before a deletion, check pos != -1.

When the same value appears in several cells after a shift, the loop ran in the wrong direction.

The rules in table form

Each row reads from left to right: the assumptions, then the result. A red cell is not an answer, it is the finding that the form settles nothing and the instruction to rewrite it. Every case is followed by a worked example.

Starting values, algorithm by algorithm

Each row was run in Python 3 on a = [-6, -2, -8, -2, -5], an array of negative values.

AlgorithmStart before the loopResult for a
count of a[i] > -5 count = 0 2

Example: -2 and -2 pass the test; -5 does not, since > excludes the bound.

total total = 0 -23

Example: -6 - 2 - 8 - 2 - 5 = -23: 0 is the right start for a sum, whatever the signs.

average total / len(a) -4.6

Example: -23 / 5 = -4.6, computed after the loop.

largest and where largest = a[0], where = 0 -2 at index 1

Example: -2 > -6 at i = 1; at i = 3, -2 > -2 is False, so where keeps the first occurrence.

largest largest = 0 0 not in the array

Example: No element is above 0, so the start is never beaten.

What to do: Start from a[0]: a real element of the array is always a possible answer.

smallest smallest = a[0] -8

Example: -8 < -6 at i = 2, and nothing is below -8 after it.

search for -2 pos = -1 1, after 2 comparisons

Example: The loop stops at the first match; the second -2, at index 3, is never compared.

search for 7 pos = -1 -1, after 5 comparisons

Example: 7 matches none of the 5 elements: 5 comparisons, and only then is it declared absent.

average of [] total / len(a) ZeroDivisionError no average

Example: With no element, total = 0 and len(a) = 0: 0 / 0.

What to do: Test len(a) > 0 before the division, and print a message otherwise.

A start is right if it is the correct answer for an array the loop has not looked at yet: 0 elements for a count, a[0] alone for a maximum.

The mistakes that cost marks

These are the errors I correct most often in session. Each one costs marks on a paper, even when the reasoning behind it is right.

1. A maximum that starts at 0

1 to 2 marks: a wrong answer on every array of negative values

What not to write

“largest = 0, then for i in range(len(a)): if a[i] > largest: largest = a[i].”

What to write

“largest = a[0], then for i in range(1, len(a)): if a[i] > largest: largest = a[i]. For [-6, -2, -8, -2, -5], it gives -2.”

Why: 0 is not an element of the array; on negative values no element beats it, and the program prints 0 with no error.

2. Not found printed inside the loop

1 to 2 marks: one line per element, and Not found for a value that is there

What not to write

“for i in range(len(a)): if a[i] == target: print('Found') else: print('Not found')”

What to write

“pos = -1, then the loop sets pos = i on a match; after the loop, if pos == -1: print('Not found'), else print the position.”

Why: Absent is a statement about every element, so it can only be concluded once the last one has been compared.

3. A found flag reset at every pass

1 mark: the result describes the last element only

What not to write

“if a[i] == target: found = True else: found = False, inside the loop.”

What to write

“found = False before the loop; inside, only if a[i] == target: found = True. Nothing sets it back to False.”

Why: The else rewrites the flag after the match, so the program says True only when the target is the last element.

4. An insertion shifted from the left

2 marks: every value after the insertion point is lost

What not to write

“5 goes at index 1, so for j in range(1, size): a[j + 1] = a[j], then a[1] = 5.”

What to write

“Shift from the right: i = size - 1, while i >= 0 and a[i] > 5: a[i + 1] = a[i], i = i - 1; then a[i + 1] = 5.”

Inserting 5 into [3, 8, 14, 20], size 4index012345beforefrom the rightfrom the left3814200035814200358880
From the right, 8, 14 and 20 each move one cell; from the left, 8 is copied three times and 14 and 20 are lost.

Why: From the left, each copy goes into a cell that has not been saved yet, so the first copied value spreads to the end.

5. A deletion that keeps size

1 mark: the last value appears twice

What not to write

“for i in range(pos, size - 1): a[i] = a[i + 1], then print the cells 0 to size - 1.”

What to write

“After the shifts, size = size - 1: the last value, copied one cell to the left, is then outside the cells in use.”

Deleting a[1] = 34 from [21, 34, 55, 89], size 4index01234beforesize kept at 4size = 3213455890215589890215589890
After the shifts, 89 is in cells 2 and 3; with size kept at 4 it is printed twice, with size = 3 cell 3 is spare.

Why: The shifts copy the last value one cell to the left but do not erase it; only size says it is no longer in use.

6. A deletion shifted from the right

2 marks: one value copied over all the others

What not to write

“for i in range(size - 2, pos - 1, -1): a[i] = a[i + 1], to fill the gap at pos.”

What to write

“for i in range(pos, size - 1): a[i] = a[i + 1], from the gap upwards.”

Why: From the right, a[size - 2] receives the last value, then a[size - 3] receives that same value, and so on down to pos.

7. The average of an empty array

1 mark: the program stops with a ZeroDivisionError

What not to write

“average = total / len(a)” with no test, for an array that may be empty.

What to write

“if len(a) > 0: average = total / len(a) else: print('No values')”

Why: With no element, the division is 0 / 0, and Python stops the program.

8. The position -1 used as an index

2 marks: the wrong element is deleted

What not to write

“pos = position found by the search; for k in range(pos, size - 1): a[k] = a[k + 1]; size = size - 1.”

What to write

“if pos == -1: print('Not found') else: the shifts and size = size - 1.”

Why: With pos = -1, range(-1, size - 1) shifts every element from a[0] on, and Python reads a[-1] as the last cell with no error; Java stops with an ArrayIndexOutOfBoundsException.

9. A tie read with the wrong comparison

1 mark: a wrong index

What not to write

“> or >=, it does not matter: the largest value is the same.”

What to write

“The value is the same, but > keeps the index of the first occurrence and >= the last. The question says which one is wanted.”

Why: On a tie, only >= lets the later element replace the earlier one.

Which method to choose

Which algorithm does the question ask for?

Read the verb of the question, then pick the pattern and its start.

  • If « how many » elements meet a condition → a count: count = 0, count = count + 1 under the test

    Example: how many games were lost by 3 goals or more

  • If « in all » or « on average » → a total: total = 0, total = total + a[i]; the average after the loop, if len(a) > 0

    Example: the average goal differential of a season

  • If « the highest », « the lowest », « which one » → a maximum or minimum from a[0], with where for the index

    Example: the closest game and its number

  • If « is it there », « at which position » → a linear search: pos = -1, stop at the first match, conclude after the loop

    Example: the index of a student number, or -1

  • If « add » and the array must stay sorted → an insertion: shifts from the right, then write into the gap and size + 1

    Example: a new score in a high-score table

  • If « remove » a given value → a search for its position, then, if pos != -1, shifts to the left and size - 1

    Example: a student who leaves a waitlist

Two algorithms often chain: a search gives the position that a deletion uses, so the -1 case is handled between them.

How the answer is expected to be written

A marker ticks steps. Here they are in order, with the concluding sentence expected word for word.

Tracing an insertion or a deletion on a unit test

When to use it: « What does the array hold after line 8? », « How many times does line 6 run? », « Which value is lost? »

  1. 1 Draw the cells with their indices, and mark size: the cells in use, then the spare ones.
  2. 2 Write one row per shift: the value of i, the copy a[i + 1] = a[i] or a[i] = a[i + 1], and the array after it.
  3. 3 Stop at the first test that is false, and write the final value of i.
  4. 4 Write the last line, a[i + 1] = value or size = size - 1, and the array at the end.
  5. 5 Check the result: still sorted, every original value present once, size changed by 1.

Concluding sentence

“i = 1: 19 > 22 is False, so the loop stops after 3 shifts and line 8 writes 22 into a[2].”

The trap: Writing only the final array: one wrong shift early carries into every later row, and the method earns nothing.

Marking: A common split: 1 mark per correct state of the array, 1 for the final value of i or size.

Writing a count, a maximum or a search

When to use it: « Write the lines that count... », « Find the highest... and its position », « Print the index of..., or Not found »

  1. 1 Set the variables before the loop, with a start that is right for an array not yet read: 0, a[0] or -1.
  2. 2 Write one traversal by index, and inside it one test per thing to remember.
  3. 3 Write the conclusion after the loop: the print, the average, the Not found.
  4. 4 Add the guard for an empty array when the start reads a[0] or the conclusion divides by len(a).
  5. 5 Trace the program on a short array, on an array of negative values, and on a value that is absent.

Concluding sentence

“largest starts at a[0], so the program is right for an array of one element, and it never answers a value that is not in the array.”

The trap: Using max(), sum() or in when the question asks for the algorithm: the line is right, but the algorithm the question asks for is not written.

Marking: A common split: 1 mark for the start, 1 for the loop, 1 for the test, 1 for the conclusion after the loop.

Check before you hand in

Five minutes of checking recover more marks than one more problem started in a hurry.

  • The start on an extreme array

    Run your start in your head on an array of negative values, and on an array of one element.

    largest = 0 on [-6, -2] gives 0: wrong start.

  • One conclusion, after the loop

    A search prints one line, after the loop, and says Not found only when pos is still -1.

    Five lines printed for a five-element search means the print is inside the loop.

  • Each value once after a shift

    After an insertion or a deletion, every original value is still there exactly once in the cells in use.

    [12, 19, 22, 25, 25, 25] after inserting 22: 31 and 40 were overwritten.

  • size changed by 1

    size + 1 after an insertion, size - 1 after a deletion, and nothing if the value was not added or not found.

    A deletion that prints the last value twice forgot size - 1.

The typical problem, taken apart

Bib numbers at a charity run, kept sorted

At the check-in desk of a charity run, the bib numbers already handed out are kept in increasing order in an array of 8 cells, with size = 5. A late runner receives bib 131, then the runner with bib 117 withdraws. Trace the program below and give the bibs printed at the end.

Python
bibs = [104, 117, 123, 150, 168, 0, 0, 0]
size = 5
new = 131
i = size - 1
while i >= 0 and bibs[i] > new:
    bibs[i + 1] = bibs[i]
    i = i - 1
bibs[i + 1] = new
size = size + 1
gone = 117
pos = -1
i = 0
while i < size and pos == -1:
    if bibs[i] == gone:
        pos = i
    i = i + 1
if pos != -1:
    for k in range(pos, size - 1):
        bibs[k] = bibs[k + 1]
    size = size - 1
for k in range(size):
    print(bibs[k])

Step 1

The array: bibs = [104, 117, 123, 150, 168, 0, 0, 0], size = 5. Cells 0 to 4 are in use, cells 5 to 7 are spare.

Why

The insertion needs one spare cell: size = 5 < 8, so there is room.

Step 2

Insertion of 131, from the right: i = 4, 168 > 131, bibs[5] = 168; i = 3, 150 > 131, bibs[4] = 150; i = 2, 123 > 131 is False. Then bibs[3] = 131 and size = 6.

index01234567before131 added10411712315016800010411712313115016800

Why

Each copy goes into a cell already saved, the spare cell first; the loop stops at the first bib smaller than 131.

Step 3

Search for 117: i = 0, 104 == 117 False; i = 1, 117 == 117 True, pos = 1. 2 comparisons.

Why

The search gives the position that the deletion needs; -1 would mean that 117 is not among the cells in use.

Step 4

Deletion at pos = 1: range(1, 5) gives 1 to 4, bibs[1] = 123, bibs[2] = 131, bibs[3] = 150, bibs[4] = 168. Then size = 5.

index01234567before117 removed1041171231311501680010412313115016816800

Why

The shifts start from the gap and go up to size - 2, so each copy fills the cell just emptied.

Step 5

Output: 104, 123, 131, 150, 168, five lines. bibs[5] still holds 168, outside the cells in use.

Why

size = 5 is what keeps the second 168 from being printed.

The conclusion, written out

“After the insertion of 131 and the withdrawal of 117, the bibs in use are 104, 123, 131, 150 and 168, still in increasing order, and size = 5.”

The classic mistake on this problem: Shifting the insertion from the left, from index 3: bibs would become 104, 117, 123, 131, 150, 150, and 168 would be lost.

Learn by heart

  • • Count and total start at 0; a maximum or minimum starts at a[0]; a position starts at -1.
  • • The conclusion of a search comes after the loop.
  • • > keeps the first of a tie, >= the last.
  • • A target found first at index k costs k + 1 comparisons; an absent one costs len(a).
  • • Insertion: shift from the right, write into the gap, size + 1.
  • • Deletion: shift from pos to the right end, then size - 1.
  • • No average and no a[0] for an empty array: test len(a) first.
  • • Never use pos as an index before checking pos != -1.

Frequently asked questions

How do you find the largest value in an array without max in ICS3U?

Store the first element in a variable, largest = a[0], then loop over the indices 1 to the last one and replace largest each time an element is strictly greater. After the loop, largest holds the answer. Keep the index in a second variable if the question asks where the value is. Starting from the first element works for every array that is not empty, including an array of negative values.

Why should the maximum of an array not start at 0?

Because 0 may not be in the array. If every value is negative, no element is greater than 0, the variable is never replaced, and the program prints 0, a value that does not exist in the data, without any error message. Starting from the first element of the array avoids this, since that start is always a possible answer.

How do you insert a value into a sorted array in ICS3U?

Start at the last cell in use and move left: while the cell holds a value greater than the new one, copy it one cell to the right. When the loop stops, the cell just after the stopping point is free: write the new value there and add one to the number of cells in use. Shifting from the left instead would copy one value over all the others.

How do you delete an element from the middle of an array?

Find its position first, with a linear search. Then, from that position up to the second last cell in use, copy each next cell one step to the left, and subtract one from the number of cells in use. Without that last step, the final value appears twice. If the search returned minus one, the value is not there, and nothing must be shifted.

What does a linear search return when the value is not found?

By convention, minus one, a number that cannot be a valid index of the array, so the program can tell found from not found. The search starts with the position at minus one, changes it only on a match, and the program checks for minus one after the loop, before using the position. In Python, minus one used as an index silently reads the last cell, so the check matters.

Mark this sheet as read or add it to your favourites: a free account, no password, keeps your read sheets and favourites from one visit to the next, tells you which chapter to tackle next and lets you ask for the method or exercise you are missing. Create your space, an email is enough.

Practise it

Corrected exercises: Array algorithms, ICS3U

A method is proved on a paper, not on a sheet. The set for the same chapter takes each of these traps into a problem, with the solution written out step by step.

  • 10 corrected exercises
  • 100 points
  • 150 minutes
Do the exercises
Something missing from this sheet? A method, a trap, an exercise to practise it, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Revision sheet published at www.letuteurscientifique.ca/en/fiches/ics3u-array-algorithms. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

Preparing for an ICS3U unit test?

I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session.

Site by Studio Squalli