Binary Search

Binary search (also known as halving method or bisection) is a classic algorithm for searching for an element in a sorted array (vector), using division of the array into halves.

Algorithm and Explanation:

In functional programming, halving a linked list presents a challenge. To compute the length of a linked list, one must traverse all elements, which takes linear time. Then one must find the middle element, which also takes linear time. Altogether, if the list length is n, computing half of the list will take \(\frac{3n}{2}\) operations.

Let's try to compute half of the list in \(\frac{n}{2}\) operations. We define a "race" algorithm that computes half of the list in \(\frac{n}{2}\) operations.

oneStep will contain exactly half of the elements between list and subList, because by the time twoStep equals subList, 2k elements will have been removed from it, standing between list and subList, so k elements will have been removed from oneStep, i.e., half.

We then use the standard binary search algorithm:

Example:

Let's consider an example of computing binary search for the list List(1, 3, 5, 7, 9) and key key = 3.

Computation example:

Estimation:

Code:

import scala.annotation.tailrec
import scala.math.Ordered.orderingToOrdered

def binarySearch[A: Ordering](list: List[A], key: A): Option[A] =
  @tailrec
  def search(lst: List[A], sub: List[A]): Option[A] =
    if lst == sub then None
    else
      middle(lst, sub) match
        case Nil => None
        case head :: next =>
          if key < head then search(lst, head :: next)
          else if key > head then search(next, sub)
          else Some(head)

  def middle(lst: List[A], sub: List[A]): List[A] =
    @tailrec
    def race(oneStep: List[A], twoSteps: List[A]): List[A] =
      if twoSteps.nonEmpty && twoSteps != sub && twoSteps.tail != sub then
        race(oneStep.drop(1), twoSteps.drop(2))
      else oneStep

    race(lst, lst)

  search(list, Nil)
end binarySearch

binarySearch((1 to 100).toList, 45)
// Some(45)

Links: