Re: [R] General binary search?

From: William Dunlap <wdunlap_at_tibco.com>
Date: Mon, 04 Apr 2011 13:50:28 -0700

> -----Original Message-----
> From: r-help-bounces_at_r-project.org
> [mailto:r-help-bounces_at_r-project.org] On Behalf Of Stavros Macrakis
> Sent: Monday, April 04, 2011 1:15 PM
> To: r-help
> Subject: [R] General binary search?
>
> Is there a generic binary search routine in a standard library which
>
> a) works for character vectors
> b) runs in O(log(N)) time?
>
> I'm aware of findInterval(x,vec), but it is restricted to
> numeric vectors.

xtfrm(x) will convert a character (or other) vector to a numeric vector with the same ordering. findInterval can work on that. E.g.,

   > f0 <- function(x, vec) {
       tmp <- xtfrm(c(x, vec))
       findInterval(tmp[seq_along(x)], tmp[-seq_along(x)])
     }

   > f0(c("Baby", "Aunt", "Dog"), LETTERS)    [1] 2 1 4
I've never looked at its speed.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com

>
> I'm also aware of various hashing solutions (e.g.
> new.env(hash=TRUE) and
> fastmatch), but I need the greatest-lower-bound match in my
> application.
>
> findInterval is also slow for large N=length(vec) because of the O(N)
> checking it does, as Duncan Murdoch has pointed
> out<https://stat.ethz.ch/pipermail/r-help/2008-September/174584.html>:
> though
> its documentation says it runs in O(n * log(N)), it actually
> runs in O(n *
> log(N) + N), which is quite noticeable for largish N. But
> that is easy
> enough to work around by writing a variant of findInterval which calls
> find_interv_vec without checking.
>
> -s
>
> PS Yes, binary search is a one-liner in R, but I always prefer to use
> standard, fast native libraries when possible....
>
> binarysearch <- function(val,tab,L,H) {while (H>=L) {
> M=L+(H-L) %/% 2; if
> (tab[M]>val) H<-M-1 else if (tab[M]<val) L<-M+1 else return(M)};
> return(L-1)}
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Mon 04 Apr 2011 - 20:57:13 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 06 Apr 2011 - 17:20:28 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive