I need to write an equivalent function to the function length
-without using
length
, of course. also it must be using a loop.
I need to write two versions for this function. the first, with O(n) complexity, and the second need to be in O(log(n))
EDIT
Also, Suppose that the vector doesn't contain NA
values
My Attempt:
my_length_l <- function(x){
k <- 1
while(!is.na(x[k])){
k <- k+1
}
return(k-1)
}
for my_length_l
:
T(n) = O(n)
second version:
my_length_bs <- function(x){
if(is.na(x[2])){return(1)}
else
{
k <- 2
for(i in 1:log2(2^k)){
while(!is.na(x[k])){
k <- k+1
}
}
}
return(k-1)
}
Is my_length_bs
indeed exists T(n) = log(n)?