R Program to Implement Linear Search

R Program to Implement Linear Search

Linear Search is one of the simplest and most intuitive searching algorithms, making it an excellent starting point for beginners in R programming. It works by checking each element in a dataset sequentially until the target value is found or the list ends. While not the most efficient for large datasets compared to algorithms like Binary Search, its simplicity and versatility make it highly useful, especially when the data is unsorted or small.

Linear Search is widely used in real-life scenarios where a dataset may not be organized, such as finding a name in a small list, checking for specific numbers in an array, or locating items in a collection. For beginners, implementing Linear Search in R offers a clear introduction to loops, conditional statements, and recursion. It also lays the groundwork for understanding more advanced search algorithms later on.

Program 1: Basic Linear Search using a for loop

This program demonstrates a straightforward Linear Search using a for loop to scan through the array and return the index of the target value.

linear_search <- function(arr, target) {

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

    if (arr[i] == target) {
      return(i)
    }

  }

  return(-1)

}

data <- c(5, 3, 8, 1, 4)
target <- 8

print(linear_search(data, target))

In this program, each element is checked sequentially. If the target is found, its position is returned; otherwise, the function returns -1. This approach helps beginners understand the fundamental logic of searching element by element.

Program 2: Linear Search with a while loop

This version uses a while loop instead of a for loop, providing an alternative approach for beginners to understand loops in R.

linear_search_while <- function(arr, target) {

  i <- 1

  while (i <= length(arr)) {

    if (arr[i] == target) {
      return(i)
    }

    i <- i + 1

  }

  return(-1)

}

data <- c(2, 7, 4, 9, 1)
target <- 9

print(linear_search_while(data, target))

Using a while loop emphasizes control flow and how loops can be constructed differently while achieving the same result. Beginners learn that logic can often be expressed in multiple ways.

Program 3: Linear Search with multiple occurrences

This program searches for all occurrences of a target value and returns their positions in the array, useful when duplicates exist.

linear_search_all <- function(arr, target) {

  indices <- c()

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

    if (arr[i] == target) {
      indices <- c(indices, i)
    }

  }

  if (length(indices) == 0) return(-1)
  return(indices)

}

data <- c(4, 2, 4, 5, 4)
target <- 4

print(linear_search_all(data, target))

Beginners see how to handle multiple matches and store results in a vector. This is useful for real-world scenarios where the same value may appear more than once.

Program 4: Recursive Linear Search

This version demonstrates Linear Search using recursion, allowing learners to understand how functions can call themselves to solve problems.

linear_search_recursive <- function(arr, target, index = 1) {

  if (index > length(arr)) return(-1)
  if (arr[index] == target) return(index)

  return(linear_search_recursive(arr, target, index + 1))

}

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

print(linear_search_recursive(data, target))

Recursion provides an elegant approach and helps beginners learn how problems can be broken down into smaller, repeatable tasks. This also introduces the concept of base cases and recursive calls in programming.

Program 5: Linear Search with input validation

This program checks if the input is numeric and prints a message if the target is not found, making the program more robust.

linear_search_safe <- function(arr, target) {

  if (!is.numeric(arr)) stop("Input array must be numeric")

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

    if (arr[i] == target) {
      return(i)
    }

  }

  return("Target not found")

}

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

print(linear_search_safe(data, target))

Input validation is a useful skill for beginners, teaching them how to write safer and more reliable code. It also demonstrates simple error handling in R.

Program 6: Linear Search for character vectors

Linear Search is not limited to numbers. This version searches for a string in a character vector.

linear_search_chars <- function(arr, target) {

  for (i in 1:length(arr)) {
    if (arr[i] == target) return(i)
  }

  return(-1)

}

data <- c("Harry", "Hermione", "Ron", "Luna")
target <- "Ron"

print(linear_search_chars(data, target))

Beginners learn that the same logic can be applied to characters or strings, expanding the applicability of Linear Search to various data types.

Program 7: Linear Search with multiple character matches

This version finds all occurrences of a string in a character vector.

linear_search_chars_all <- function(arr, target) {

  indices <- c()

  for (i in 1:length(arr)) {
    if (arr[i] == target) indices <- c(indices, i)
  }

  if (length(indices) == 0) return(-1)

  return(indices)

}

data <- c("Albus", "Severus", "Albus", "Sirius")
target <- "Albus"

print(linear_search_chars_all(data, target))

It shows beginners how to adapt numeric search logic to string data while handling multiple matches.

Program 8: Linear Search in mixed numeric types

Linear Search works seamlessly with floating-point numbers as well.

linear_search <- function(arr, target) {

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

    if (arr[i] == target) {
      return(i)
    }

  }

  return(-1)

}

data <- c(1.5, 3.2, 4.8, 2.5)
target <- 4.8

print(linear_search(data, target))

This demonstrates that Linear Search is versatile and can handle integers, decimals, or mixed numeric data without modification.

Program 9: Linear Search in negative and positive numbers

This program confirms that Linear Search works with negative numbers as easily as with positive ones.

linear_search <- function(arr, target) {

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

    if (arr[i] == target) {
      return(i)
    }

  }

  return(-1)

}

data <- c(-5, -1, 2, 4, -3)
target <- -3

print(linear_search(data, target))

Beginners can see that Linear Search does not require sorted data or special handling for negative numbers, making it straightforward for everyday use.

Frequently Asked Questions (FAQ)

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

Q1. Is Linear Search efficient for large datasets?
Linear Search is simple but not efficient for very large datasets. For large sorted datasets, Binary Search is faster.

Q2. Can Linear Search handle duplicates?
Yes, you can modify the algorithm to return all indices where the target occurs.

Q3. Can Linear Search work with strings or characters?
Yes, the algorithm works the same way for character vectors.

Q4. Does the data need to be sorted?
No, Linear Search works on unsorted data, which is one of its advantages.

Conclusion

Linear Search is a beginner-friendly algorithm that introduces essential programming concepts such as loops, recursion, and conditional checks. By practicing different versions—from numeric to character searches, from loops to recursion—beginners gain a solid understanding of how searching works in R.

Exploring Linear Search with small and diverse datasets helps build confidence and prepares learners for more advanced searching and sorting techniques. Regular practice ensures that beginners not only understand the logic but can also apply it in real-world programming situations effectively.

Scroll to Top