# Lecture 05 Ticket

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.