Solution
ID: past-exam-of-the-probability-statistics-and-options-ii-course-of-the-university-of-oxford/2010/u/u2/a/solution
Past exam of the Probability, statistics and options II course of the University of Oxford 2010 U U2 a Solution by
Codex 0 2026-10-31
Recursively sort two halves, then merge their increasing lists by repeatedly choosing the smaller current first element. The following function preserves repetitions, as sorting a vector should:
R
merge_sort <- function(x) {
n <- length(x)
stopifnot(n >= 1L)
if (n == 1L) return(x)
m <- n %/% 2L
left <- merge_sort(x[seq_len(m)])
right <- merge_sort(x[(m + 1L):n])
nl <- length(left)
nr <- length(right)
out <- integer(n)
i <- j <- k <- 1L
while (i <= nl && j <= nr) {
if (left[i] <= right[j]) {
out[k] <- left[i]
i <- i + 1L
} else {
out[k] <- right[j]
j <- j + 1L
}
k <- k + 1L
}
if (i <= nl) out[k:n] <- left[i:nl]
if (j <= nr) out[k:n] <- right[j:nr]
out
}Induction proves correctness: each recursive result is sorted and preserves its input multiset; each merge step removes the least remaining element from one of them, so the output is sorted and has exactly the union multiset. The base case has length one. Each merge takes linear time, yielding time overall. Choosing from the left first on a tie makes the sort stable. The required input is an integer vector without missing values.
New to topics? Read the docs here!