Linear Search Algorithm in Scala

1. Introduction

Linear Search, also known as Sequential Search, is one of the simplest searching algorithms. It works by sequentially going through the elements of a list until the desired element is found or the list ends. Because it checks each element in sequence until it finds a match, its worst-case time complexity is O(n), where n is the number of elements in the list.

2. Implementation Steps

1. Start from the first element of the list.

2. Compare the current element with the target element.

3. If they match, return the current index.

4. If they don't match, move on to the next element.

5. Repeat steps 2-4 until the element is found or all elements have been checked.

3. Implementation in Scala

object LinearSearch {
  def search(arr: Array[Int], x: Int): Int = {
    for (i <- arr.indices) {
      if (arr(i) == x) return i
    }
    -1  // return -1 if the element is not found
  }
}
// Client code to test the linear search algorithm
val array = Array(2, 4, 0, 1, 9)
val target = 1
val result = LinearSearch.search(array, target)
if (result != -1) println(s"Element $target is present at index $result")
else println(s"Element $target is not present in the array")

Output:

Element 1 is present at index 3

Explanation:

1. The search function takes an array and a target element as its parameters.

2. It iterates through the array using a loop. For each element in the array, it checks if the current element is equal to the target element.

3. If a match is found, it returns the current index, indicating the position of the target element in the array.

4. If no match is found after checking all the elements, it returns -1 to indicate that the target element is not present in the array.

5. In the client code, based on the returned value from the search function, an appropriate message is printed.


Comments