As I understand it, you're trying to replace the following lines with R versions:
while( a[++i] < v);
while( a[--j] > v);
A simple way to write these two lines would be:
i <- i + min(which(a[(i+1):length(a)] >= v))
j <- max(which(a[1:(j-1)] <= v))
In each case, the which function is computing all the indices in which some subset of a
has the appropriate value, so it's likely less efficient than just looping in custom C/C++ code until you find the first such entry.
If efficiency is important to you, you could write a very simple Rcpp
function for this operation. Here, I've defined increment
and decrement
which do the two operations, taking particular care to convert i
and j
, which I assume are 1-indexed in the R code, to a 0-indexed value in the C++ code:
library(Rcpp)
increment <- cppFunction("
int increment(NumericVector a, int i, const double v) {
while( a[(++i)-1] < v) ;
return i;
}")
decrement <- cppFunction("
int decrement(NumericVector a, int j, const double v) {
while( a[(--j)-1] > v) ;
return j;
}")
Then you could convert your two lines to i <- increment(a, i, v)
and j <- decrement(a, j, v)
.