Please download the file homework7.R and write your results there. Send the your answers to my mailbox.
1. Exploring vectors
You will program your own version of some standard functions using
only for()
, if()
and indices. All the
following functions receive a vector.
Please write your version of the following functions:
vector_min(x)
, equivalent tomin(x)
. Returns the smallest element inx
.vector_max(x)
, equivalent tomax(x)
. Returns the largest element inx
.vector_which_min(x)
, equivalent towhich_min(x)
. Returns the index of the smallest element inx
.vector_which_max(x)
, equivalent towhich_max(x)
. Returns the index of the largest element inx
.
You can test your function with the following code.
<- sample(5:20, size=10, replace=TRUE)
x min(x)
vector_min(x)
The two results must be the same. Obviously, you have to replace
min
and vector_min
with the corresponding
functions.
2. Merging vectors
Please write a function called vector_merge(x, y)
that
receives two sorted vectors x
and
y
and returns a new vector with the elements of
x
and y
together sorted. The
output vector has size length(x)+length(y)
.
You must assume that each of the input vectors is already sorted.
For that you have to use three indices: i
,
j
, and k
; to point into x
,
y
and the output vector ans
. On each step you
have to compare x[i]
and y[j]
. If
x[i] < y[j]
then ans[k] <- x[i]
,
otherwise ans[k] <- y[j]
.
When either of the input vectors is finished, the remaining of the other input vector must be copied to the output vector.
You have to increment i
or j
, and
k
carefully. To test your function, you can use this
code:
<- sample(letters)
a <- sort(a[1:13])
x <- sort(a[14:26])
y print(x)
[1] "c" "f" "g" "i" "k" "l" "q" "t" "u" "v" "w" "x" "z"
print(y)
[1] "a" "b" "d" "e" "h" "j" "m" "n" "o" "p" "r" "s" "y"
vector_merge(x,y)
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p"
[17] "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"
The output must be a sorted alphabet.
Sorting
Please write a function called vector_mergesort(x)
that
takes a single vector x
and returns a new vector with the
same elements of x
but sorted from the smallest to the
largest.
To do so you have to use a recursive strategy as follows:
- If the input vector
x
has length 1, then it is already sorted. In that case the output is a copy ofx
- If the length of the input is larger than 1 then you split
x
in two parts. The new vectorx1
contains the first half ofx
, andx2
has the second half. - Be careful when
length(x)
is odd. - Now you have to sort
x1
andx2
by using the same functionvector_mergesort()
. Store the results inans1
andans2
. - Finally you have to merge
ans1
andans2
using the functionvector_merge()
of the previous exercise, and return the merged vector.
How can you test this function?
Remember: The more exercises you do, the more chances you have to pass the course.