25-Comp-A4 Program Design and Data Structures · December 2018
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer)
Paper format. 17-Comp-A4 Program Design and Data Structures, December 2018 — 3 hours, closed book, no calculator permitted. Nine questions, each of equal weight (Question 1 is split 10+10; Questions 2–9 are 20 marks each); candidates answer any six, and only the first six as they appear in the answer book are marked, so the paper is marked out of 120. Pseudocode or any high-level language (e.g. C or C++) is accepted, and the examiner's note states explicitly that marking emphasises the operation of the program, not syntactic details. All nine questions are answered below, because the whole set is the more useful revision resource. Answers are given in C or C++ as the question dictates; each is compilable as written, but a clear, correctly reasoned pseudocode answer would earn the same marks.
Reference texts for this subject.
The Computer Engineering citation list is built around architecture and networking texts (Patterson & Hennessy, Tanenbaum, Mano); this subject is programming and data structures, so the works above are cited instead.
Question text not reproduced: the examination questions are © Engineers and Geoscientists BC. Open the official past paper (linked at the top of this page) to read the question, then follow the worked solution below.
Given. An array of length $n$ holding only the values 0 and 1, in the arbitrary order shown above.
Find. The same array rearranged so every 0 precedes every 1, using exactly one traversal and no sorting routine or separate counting pass.
Approach. Maintain two pointers, left and
right, starting at the two ends of the array and moving toward
each other. Advance left past any 0 already in place, retreat
right past any 1 already in place, and when left
sits on a 1 and right sits on a 0, swap them — a
two-pointer scheme that is a two-value special case of the Dutch national
flag partition, and touches each array slot a bounded number of times.
#include <stdio.h>
void partition_zeros_ones(int a[], int n)
{
int left = 0, right = n - 1, tmp;
while (left < right) {
if (a[left] == 0) {
left++; /* already in place, move on */
} else if (a[right] == 1) {
right--; /* already in place, move on */
} else { /* a[left]==1 and a[right]==0: swap */
tmp = a[left];
a[left] = a[right];
a[right] = tmp;
left++;
right--;
}
}
}| Quantity | Value |
|---|---|
| Array length $n$ | 15 |
| Zeros / ones in the input | 9 / 6 |
| Partitioned output | 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 |
| Passes over the array | 1 (two pointers, no sort, no counting pass) |