From 7620449322d93beb2c62c3226e3851f867bf4e5f Mon Sep 17 00:00:00 2001 From: Robson Cruz Date: Wed, 19 Jul 2023 12:53:24 -0300 Subject: [PATCH] Added R version of the binary_search function (#253) --- .../R/binary_search.R | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 01_introduction_to_algorithms/R/binary_search.R diff --git a/01_introduction_to_algorithms/R/binary_search.R b/01_introduction_to_algorithms/R/binary_search.R new file mode 100644 index 0000000..7d91407 --- /dev/null +++ b/01_introduction_to_algorithms/R/binary_search.R @@ -0,0 +1,37 @@ +binary_search <- function(list, item) { + # low and high keep track of which part of the list you'll search in. + # Every data structure in R indexed by starting at 1. + low <- 1 + high <- length(list) + + # While you haven't narrowed it down to one element ... + while (low <= high) { + # ... check the middle element + mid <- (low + high) %/% 2 + guess <- list[mid] + # Found the item. + if (guess == item) { + return(mid) + } + # The guess was too high. + else if (guess > item) { + high <- mid - 1 + } + else{ # The guess was too low. + low <- mid + 1 + } + } + # Item doesn't exist + return(NULL) +} + + +# Set a list +my_list <- list(1, 3, 5, 7, 9) + +# Call the function +binary_search(my_list, 3) # => 1 +binary_search(my_list, -1) # => NULL + +# All above code can be simplified by using "which" function +which(my_list == 3) # => 1