# Lecture 05 Ticket Solution

Complete before the beginning of class on Monday, 09/12. (Will be graded for completion not correctness.)

Download this ticket in pdf format or .tex source.

\[\def\compare{ {\mathrm{compare}} } \def\swap{ {\mathrm{swap}} } \def\sort{ {\mathrm{sort}} } \def\true{ {\mathrm{true}} } \def\false{ {\mathrm{false}} }\]Consider the following method that takes two arrays of numerical values, \(a\) and \(b\) as input and returns another array \(c\):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Merge(a, b):
i, j, k <- 1
c <- new array of size size(a) + size(b)
while i <= size(a) and j <= size(b) do
if a[i] <= b[j] then
min <- a[i]
i <- i + 1
else
min <- b[j]
j <- j + 1
endif
c[k] <- min
k <- k + 1
endwhile
while i <= size(a) do
c[k] <- a[i]
i <- i + 1
k <- k + 1
endwhile
while j <= size(b) do
c[k] <- b[j]
j <- j + 1
k <- k + 1
endwhile
return c

Argue that if \(a\) and \(b\) are sorted, then the array \(c\) returned by \(\mathrm{Merge}(a, b)\) is sorted and contains every element from both \(a\) and \(b\). Your argument does not have to be too formal, but you should describe a loop invariant for the first while loop that explains *how* the procedure creates a sorted array.

### Solution

Consider the first while loop on lines 4–14. In iteration \(k\), this loop selects the smaller of the values \(a[i]\) and \(b[j]\) and copies it to \(c[k]\), then increments \(k\) as well as the index (\(i\) or \(j\)) of the copied element. Since \(a\) and \(b\) are assumed to be sorted, this procedure always selects the smallest element from \(a\) and \(b\) that has not yet been copied to \(c\). In particular, after iteration \(k\), \(c\) contains the \(k\) smallest elements from \(a\) and \(b\) in sorted order.

The first loop terminates when all of the element from \(a\) or \(b\) have been copied to \(c\). The second and third while loops (lines 16–26) copy the remaining elements to \(c\).