4. Below we ask you to represent integer sequences using the C++ std::vector class
from the standard template library. A useful method to recall on vectors is the method
push_back.
(a) Write a function splitInto that takes three arguments, each being a vector of inte-
gers. The first is named array and is passed by value. The second named evens is
passed by reference. The third is named odds and is also passed by reference. You
can assume that array has a size of at least two, and that evens and odds each have
size 0. Upon completion of splitInto, evens should contain the sequence of items
of array at even positions (item 0, item 2, item 4, etc.) and odds should contain the
sequence of items of array at odd positions (item 1, item 3, item 5, etc.).
(b) Write a function merge that takes two arguments, each being a vector of integers,
named array1 and array2, and passed by value. You can assume that array1 and
array2 each have a size of at least one and are sorted. The function should return a
new vector containing the items of both, and in sorted order. For example, if the first
contains the sequence 0,3,4,5,18 and the second contains the sequence 2,4,6,7,11 then
it should give back a new vector with the sequence 0,2,3,4,4,5,6,7,11,18.
(c) Now write a recursive function mergeSort that uses these two functions. It takes
an integer vector named array and it is passed by value. It should return back an
integer vector with the same size and storing the same integer values, but in sorted
order. It should do this using this algorithm:
If the vector it is given has size less than two, then that array is already sorted, so
it can just return that array back. If the size is two or greater, then it splits the
vector into two vectors, the even-indexed items and the odd-indexed items, with
splitInto. It then calls mergeSort on each of those vectors individually, thus
making two different recursive calls. It gets back two sorted vectors, one with each
call. It then merges these two vectors into a single vector using merge and returns
that sorted result.
When given a vector containing 18,7,4,6,5,4,3,2,0,11, it should split them into 18,4,5,3,0
and 7,6,4,2,11. It then sorts each making two new vectors with 0,3,4,5,18 and 2,4,6,7,11.
It then merges them into a new vector with 0,2,3,4,4,5,6,7,11,18.