Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2015/imperative-programming/3/e/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2015 Imperative programming 3 e Solution by
Codex 0 2026-10-31
Assume The loop invariant says that the segment from
less is a lawful strict comparison, for example a strict weak order, and the two input linked lists are disjoint and sorted by it. Allocate a result header and move existing data linked list nodes; do not copy their values.PROCEDURE Merge(less: LESS; q, r: List; VAR p: List);
VAR result: List; last, a, b: Tail;
BEGIN
NEW(result); result.count := q.count + r.count;
result.tail := NIL; last := result;
a := q.tail; b := r.tail;
WHILE (a # NIL) & (b # NIL) DO
IF less(b,a) THEN
last.tail := b; b := b.tail
ELSE
last.tail := a; a := a.tail
END;
last := last.tail
END;
IF a # NIL THEN last.tail := a ELSE last.tail := b END;
q.tail := NIL; q.count := 0;
r.tail := NIL; r.count := 0;
p := result
END Merge;result.tail through last is a sorted prefix of the desired merge algorithm, containing exactly the nodes already removed from the two unread chains. Every element of this prefix is no greater than either unread head. Choosing the smaller unread head maintains this property; choosing from q on a tie also gives stable sorting. New to topics? Read the docs here!