Scala Program to Implement Linear Search

Scala Program to Implement Linear Search

Linear Search is one of the simplest search algorithms in programming. The idea is straightforward: you start at the beginning of a list or array and check each element one by one until you find the target value or reach the end of the array. Even though it is not the fastest search method for large datasets, Linear Search is easy to understand and implement, making it perfect for beginners learning the basics of searching in Scala.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Linear Search is used in situations where the dataset is small, or when data is unsorted, because it does not require any prior ordering. It helps beginners grasp fundamental concepts like loops, conditionals, and basic algorithmic thinking. By learning Linear Search in Scala, programmers can also build a foundation for understanding more advanced search algorithms like Binary Search or Hashing techniques.

Program 1: Linear Search Using a Simple For Loop

This program demonstrates a basic Linear Search on an array of integers using a simple for loop.

object LinearSearchBasic {

  def linearSearch(arr: Array[Int], target: Int): Int = {

    for (i <- arr.indices) {
      if (arr(i) == target) return i
    }

    -1

  }

  def main(args: Array[String]): Unit = {

    val data = Array(5, 2, 8, 1, 9)
    val target = 8
    val index = linearSearch(data, target)

    if (index != -1) println(s"Element $target found at index $index")
    else println(s"Element $target not found")

  }

}

In this example, the loop iterates through the array, comparing each element to the target. If it finds a match, it returns the index. Beginners can see clearly how a simple search works and understand the concept of returning a result when a condition is met.

Program 2: Linear Search Using While Loop

This version uses a while loop instead of a for loop, which shows another way to traverse an array.

object LinearSearchWhile {

  def linearSearch(arr: Array[Int], target: Int): Int = {

    var i = 0

    while (i < arr.length) {
      if (arr(i) == target) return i
      i += 1
    }

    -1

  }

  def main(args: Array[String]): Unit = {

    val data = Array(10, 15, 20, 25, 30)
    val target = 25
    val index = linearSearch(data, target)

    if (index != -1) println(s"Element $target found at index $index")
    else println(s"Element $target not found")

  }

}

Using a while loop helps beginners understand loop control and counters. It works the same as the for loop, but the structure is slightly different, providing flexibility in how arrays are traversed.

Program 3: Recursive Linear Search

This program demonstrates a recursive approach to Linear Search, showing an alternative method without explicit loops.

object LinearSearchRecursive {

  def linearSearch(arr: Array[Int], target: Int, index: Int = 0): Int = {

    if (index >= arr.length) -1
    else if (arr(index) == target) index
    else linearSearch(arr, target, index + 1)

  }

  def main(args: Array[String]): Unit = {

    val data = Array(3, 6, 9, 12, 15)
    val target = 12
    val index = linearSearch(data, target)

    if (index != -1) println(s"Element $target found at index $index")
    else println(s"Element $target not found")

  }

}

Recursion provides a clean and elegant way to implement Linear Search. Beginners can see how a function can call itself to solve smaller instances of the same problem, building their understanding of recursive thinking.

Program 4: Linear Search for Strings

This example shows how Linear Search can be applied to arrays of strings instead of numbers.

object LinearSearchStrings {

  def linearSearch(arr: Array[String], target: String): Int = {

    for (i <- arr.indices) {
      if (arr(i) == target) return i
    }

    -1

  }

  def main(args: Array[String]): Unit = {

    val words = Array("apple", "banana", "cherry", "date")
    val target = "cherry"
    val index = linearSearch(words, target)

    if (index != -1) println(s"Word '$target' found at index $index")
    else println(s"Word '$target' not found")

  }

}

Searching for strings teaches beginners that Linear Search is versatile and can work with any data type that supports equality checking. The logic remains the same, making it easy to generalize.

Program 5: Linear Search for Multiple Occurrences

This program finds all occurrences of a target in an array, not just the first match.

object LinearSearchMultiple {

  def linearSearch(arr: Array[Int], target: Int): Array[Int] = {

    val indices = scala.collection.mutable.ArrayBuffer[Int]()

    for (i <- arr.indices) {
      if (arr(i) == target) indices += i
    }

    indices.toArray

  }

  def main(args: Array[String]): Unit = {

    val data = Array(2, 5, 2, 7, 2)
    val target = 2
    val indices = linearSearch(data, target)

    if (indices.nonEmpty) println(s"Element $target found at indices: ${indices.mkString(", ")}")
    else println(s"Element $target not found")

  }

}

By collecting all matching indices, this program shows a more advanced use of Linear Search. Beginners can learn how to handle multiple matches and work with mutable collections in Scala.

Frequently Asked Questions (FAQ)

This section answers common questions beginners have when learning Linear Search in Scala.

Q1: What is Linear Search?
Linear Search is a method of finding a target element by checking each element of a list or array one by one until it is found.

Q2: When should I use Linear Search?
Use Linear Search for small or unsorted datasets where simplicity is more important than speed.

Q3: Can Linear Search handle strings?
Yes, Linear Search works for any data type that can be compared for equality, including strings.

Q4: Is Linear Search fast?
Linear Search is simple but not fast for large datasets. Its time complexity is O(n), which means performance decreases linearly with size.

Q5: Can Linear Search find multiple occurrences?
Yes, it can be adapted to find all instances of a target by storing matching indices.

Conclusion

Linear Search is a fundamental algorithm that every beginner should understand. It introduces basic programming concepts such as loops, recursion, conditionals, and array traversal. By practicing Linear Search with integers, strings, and multiple occurrences, beginners build confidence in handling arrays and implementing simple algorithms. Mastering Linear Search in Scala provides a solid stepping stone for learning more advanced search techniques like Binary Search or Hash Tables, laying the groundwork for efficient problem-solving in programming.

Scroll to Top