R Program to Implement Binary Search

R Program to Implement Binary Search

Binary Search is a highly efficient searching algorithm that makes finding elements in a sorted dataset fast and reliable. Unlike Linear Search, which checks each element one by one, Binary Search repeatedly divides the search interval in half. This divide-and-conquer approach reduces the number of comparisons significantly, making it a preferred choice for large datasets.

This algorithm is widely used in real-world applications, such as searching in sorted arrays, database indexing, and even in coding interviews. For beginners, learning Binary Search in R provides a strong foundation in algorithms and problem-solving. It also introduces important concepts such as recursion, loops, and the significance of sorted data when performing efficient searches.

Program 1: Basic Binary Search using a while loop

This program demonstrates a simple Binary Search using a while loop, which checks elements in a sorted array by repeatedly dividing the search interval in half.

binary_search <- function(arr, target) {

  left <- 1
  right <- length(arr)

  while (left <= right) {

    mid <- floor((left + right) / 2)

    if (arr[mid] == target) {
      return(mid)
    } else if (arr[mid] < target) {
      left <- mid + 1
    } else {
      right <- mid - 1
    }

  }

  return(-1)

}

data <- c(1, 3, 5, 7, 9)
target <- 5

print(binary_search(data, target))

Here, the array is split repeatedly until the target is found or the interval becomes empty. Beginners learn how Binary Search leverages sorted data for speed, making it much faster than checking each element sequentially.

Program 2: Binary Search using recursion

This version demonstrates Binary Search with a recursive approach, which is elegant and highlights how problems can be solved by breaking them into smaller subproblems.

binary_search_recursive <- function(arr, target, left = 1, right = length(arr)) {

  if (left > right) return(-1)

  mid <- floor((left + right) / 2)

  if (arr[mid] == target) return(mid)
  if (arr[mid] < target) {
    return(binary_search_recursive(arr, target, mid + 1, right))
  } else {
    return(binary_search_recursive(arr, target, left, mid - 1))
  }

}

data <- c(2, 4, 6, 8, 10)
target <- 8

print(binary_search_recursive(data, target))

Recursion helps beginners understand how algorithms can call themselves with adjusted parameters. It also shows how Binary Search naturally fits the divide-and-conquer strategy.

Program 3: Binary Search with input validation

This program adds checks to ensure the input array is numeric and sorted, making the program more robust for beginners to learn good practices.

binary_search <- function(arr, target) {

  left <- 1
  right <- length(arr)

  while (left <= right) {

    mid <- floor((left + right) / 2)

    if (arr[mid] == target) {
      return(mid)
    } else if (arr[mid] < target) {
      left <- mid + 1
    } else {
      right <- mid - 1
    }

  }

  return(-1)

}

binary_search_safe <- function(arr, target) {

  if (!is.numeric(arr)) stop("Input must be numeric")
  if (!all(diff(arr) >= 0)) stop("Array must be sorted in ascending order")

  binary_search(arr, target)

}

data <- c(1, 2, 4, 6, 8)
target <- 4

print(binary_search_safe(data, target))

Validating input teaches beginners how to prevent common errors and write more reliable code. It also emphasizes that Binary Search only works correctly on sorted arrays.

Program 4: Binary Search for negative and floating-point numbers

Binary Search works with negative numbers and decimals, as long as the array is sorted.

binary_search <- function(arr, target) {

  left <- 1
  right <- length(arr)

  while (left <= right) {

    mid <- floor((left + right) / 2)

    if (arr[mid] == target) {
      return(mid)
    } else if (arr[mid] < target) {
      left <- mid + 1
    } else {
      right <- mid - 1
    }

  }

  return(-1)

}

data <- c(-5, -2, 0, 3.5, 7.2)
target <- 3.5

print(binary_search(data, target))

This demonstrates that Binary Search is versatile and can be applied to any numeric data type, not just integers. Beginners see that the same logic applies for negative numbers and decimals without modification.

Program 5: Binary Search with detailed output

This version prints the current search interval at each step, helping beginners visualize how the algorithm narrows down the search.

binary_search_verbose <- function(arr, target) {

  left <- 1
  right <- length(arr)

  while (left <= right) {

    mid <- floor((left + right) / 2)
    print(paste("Searching between indices", left, "and", right, "mid:", mid))

    if (arr[mid] == target) {
      return(mid)
    } else if (arr[mid] < target) {
      left <- mid + 1
    } else {
      right <- mid - 1
    }

  }

  return(-1)

}

data <- c(1, 3, 5, 7, 9)
target <- 7

print(binary_search_verbose(data, target))

By observing the interval shrink, beginners better understand the efficiency of Binary Search and why it is faster than Linear Search.

Program 6: Binary Search using a for loop (less common approach)

Though loops are usually while-based, this example shows how a for loop can simulate the process.

binary_search_for <- function(arr, target) {

  left <- 1
  right <- length(arr)

  for (i in 1:length(arr)) {

    if (left > right) break

    mid <- floor((left + right) / 2)

    if (arr[mid] == target) return(mid)

    if (arr[mid] < target) {
      left <- mid + 1
    } else {
      right <- mid - 1
    }

  }

  return(-1)

}

data <- c(2, 4, 6, 8, 10)
target <- 6

print(binary_search_for(data, target))

This approach helps beginners see that different loop structures can achieve the same logic, emphasizing flexibility in programming.

Program 7: Binary Search for larger datasets

This program demonstrates Binary Search on a larger array, showing its efficiency compared to Linear Search.

binary_search <- function(arr, target) {

  left <- 1
  right <- length(arr)

  while (left <= right) {

    mid <- floor((left + right) / 2)

    if (arr[mid] == target) {
      return(mid)
    } else if (arr[mid] < target) {
      left <- mid + 1
    } else {
      right <- mid - 1
    }

  }

  return(-1)

}

data <- seq(1, 1000, by = 2)
target <- 789

print(binary_search(data, target))

For beginners, this highlights how Binary Search’s logarithmic time complexity allows it to find elements quickly even in large datasets.

Program 8: Binary Search for multiple occurrences

Binary Search typically finds a single instance, but this version finds the first occurrence in case of duplicates.

binary_search_first <- function(arr, target) {

  left <- 1
  right <- length(arr)
  result <- -1

  while (left <= right) {

    mid <- floor((left + right) / 2)

    if (arr[mid] == target) {
      result <- mid
      right <- mid - 1
    } else if (arr[mid] < target) {
      left <- mid + 1
    } else {
      right <- mid - 1
    }

  }

  return(result)

}

data <- c(1, 3, 3, 3, 5, 7)
target <- 3

print(binary_search_first(data, target))

Beginners learn how Binary Search can be adapted to solve more specific problems, such as locating the first occurrence of a repeated value.

Program 9: Binary Search in descending order

Binary Search can also work on descending-sorted arrays with a minor adjustment.

binary_search_desc <- function(arr, target) {

  left <- 1
  right <- length(arr)

  while (left <= right) {

    mid <- floor((left + right) / 2)

    if (arr[mid] == target) return(mid)

    if (arr[mid] > target) {
      left <- mid + 1
    } else {
      right <- mid - 1
    }

  }

  return(-1)

}

data <- c(10, 8, 6, 4, 2)
target <- 6

print(binary_search_desc(data, target))

This shows that with a small change in comparison logic, Binary Search is flexible and can handle both ascending and descending order arrays.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Binary Search in R.

Q1. Can Binary Search work on unsorted arrays?
No, Binary Search requires a sorted array to work correctly. For unsorted data, use Linear Search.

Q2. Is Binary Search faster than Linear Search?
Yes, Binary Search has logarithmic time complexity, making it much faster for large datasets compared to Linear Search’s linear time.

Q3. Can Binary Search find duplicates?
Binary Search typically finds one occurrence, but it can be adapted to locate first or last occurrences.

Q4. Does Binary Search work with negative or decimal numbers?
Yes, as long as the array is sorted, it works for any numeric values including negatives and decimals.

Conclusion

Binary Search is an essential algorithm for beginners to learn because of its efficiency and wide applicability. By practicing different implementations—from loops to recursion, from ascending to descending order, and handling duplicates—beginners can gain a strong understanding of search algorithms in R.

Exploring these variations also teaches important programming concepts like control flow, recursion, and problem-solving techniques. Regular practice with Binary Search prepares learners for more advanced data handling and algorithmic challenges in R programming.

Scroll to Top