Back to Challenge Set 20

Pseudocode Challenge: Tracing a Sort

Difficulty  

divider

Objective

Three problems about moving values around inside a list — Activity 2.12, in exam notation. The third shows one of the biggest differences between exam notation and C# in the whole course, and it is worth more than the other two put together.

Work these on paper. There is no computer on exam day.


Reference Card

What you are allowed to use
aList ← bList assigns a COPY of bList:
changing one does NOT change the other
aList[i] the element at i; THE FIRST IS aList[1]
aList[i] ← x store x at position i
aList[i] ← aList[j] copy one element onto another
LENGTH(aList) how many elements
FOR EACH item IN aList first to last
REPEAT UNTIL(condition) repeats UNTIL it becomes true
DISPLAY(expression) show it, FOLLOWED BY A SPACE

The Problems

Problem 1 — Trace

What does this display?

Problem 1
aList ← [7, 2, 9, 4]
temp ← aList[1]
aList[1] ← aList[3]
aList[3] ← temp
FOR EACH item IN aList
{
DISPLAY(item)
}

Then answer this: delete the second and fourth lines, so only aList[1] ← aList[3] is left of the swap. What does the list hold now, and which value is gone for good?

Problem 2 — Trace

This is one pass of selection sort. What does it display?

Problem 2
aList ← [42, 17, 93, 8, 55]
smallest ← 1
j ← 2
REPEAT UNTIL(j > LENGTH(aList))
{
IF(aList[j] < aList[smallest])
{
smallest ← j
}
j ← j + 1
}
temp ← aList[1]
aList[1] ← aList[smallest]
aList[smallest] ← temp
DISPLAY(smallest)
FOR EACH item IN aList
{
DISPLAY(item)
}

Then answer this: the list is not sorted when this finishes. How many more passes would selection sort make, and which position does the next pass fill?

Problem 3 — Trace

aList gets sorted. What do the two loops at the bottom display?

Problem 3
bList ← [5, 1, 3]
aList ← bList
i ← 1
REPEAT UNTIL(i > LENGTH(aList) - 1)
{
smallest ← i
j ← i + 1
REPEAT UNTIL(j > LENGTH(aList))
{
IF(aList[j] < aList[smallest])
{
smallest ← j
}
j ← j + 1
}
temp ← aList[i]
aList[i] ← aList[smallest]
aList[smallest] ← temp
i ← i + 1
}
FOR EACH item IN aList
{
DISPLAY(item)
}
FOR EACH item IN bList
{
DISPLAY(item)
}

Then answer this, and it is the whole problem: in C#, the first two lines would be written like this.

C#
int[] bList = { 5, 1, 3 };
int[] aList = bList;

The C# program would display something different for bList. Say what, and why — Activity 1.23 is where you met this. Then say which answer the exam expects.


Submit

  • What each problem displays, and your answers to the three Then questions
  • For Problem 3, both versions of what bList displays: exam notation and C#

This is graded on completion, not accuracy. Show your working — a wrong answer with visible reasoning is worth more to both of us than a right one with none.

Commence Challenge