search for: lastindexlessthan

Displaying 1 result from an estimated 1 matches for "lastindexlessthan".

2002 Jun 27
2
Fastest way to find the last index k such that x[k] < y in a sorted vector x?
Hi, I am trying to find the fastest way to "find the last index k such that x[k] < y in a *sorted* vector x" These are my two alternatives: x <- sort(rnorm(1e4)) y <- 0.2 # Alt 1 k <- max(1, sum(x < y)) # Alt 2 "divide and conquer" lastIndexLessThan <- function(x, y) { k0 <- 1; k1 <- length(x) while ((dk <- (k1 - k0)) > 1) { k <- k0 + dk %/% 2 if (x[k] < y) k0 <- k else k1 <- k } k0 } k <- lastIndexLessThan(x, y) Simple benchmarking shows that alternative 1 is faster for short vect...