typestar

Binary search in R

Halve the range each step, with R's one-based indexing to watch.

binary_search <- function(items, target) {
  lo <- 1
  hi <- length(items)
  while (lo <= hi) {
    mid <- (lo + hi) %/% 2
    if (items[mid] == target) {
      return(mid)
    }
    if (items[mid] < target) {
      lo <- mid + 1
    } else {
      hi <- mid - 1
    }
  }
  -1
}

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
227
Tokens
76
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 51 seconds.

Type this snippet

Step 4 of 5 in Vectorized thinking, step 13 of 20 in Language basics.

← Previous Next →

Binary search in other languages