Please download the file quiz4.R and write your results there. Send the your answers to my mailbox.
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 to min(x)
. Returns the smallest element in x
.vector_max(x)
, equivalent to max(x)
. Returns the largest element in x
.vector_which_min(x)
, equivalent to which_min(x)
. Returns the index of the smallest element in x
.vector_which_max(x)
, equivalent to which_max(x)
. Returns the index of the largest element in x
.You can test your function with the following code.
The two results must be the same. Obviously, you have to replace min
and vector_min
with the corresponding functions.
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]
.
You have to increment i
or j
, and k
carefully. To test your function, you can use this code:
The output must be a sorted alphabet.
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:
x
has length 1, then it is already sorted. In that case the output is a copy of x
x
in two parts. The new vector x1
contains the first half of x
, and x2
has the second half.length(x)
is even.x1
and x2
by using the same function vector_merge()
. Store the results in a1
and a2
.a1
and a2
using the function vector_merge()
of the previous exercise, and return the merged vectorHow can you test this function?
Remember: The more exercises you do, the more chances you have to pass the course.