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.
- Step 1 (Initialization). We define two lists:
listandsubList, where the second is always a sublist of the first. The initial values: the original list and an empty list. - Step 2 (Determining the cut). We define two lists:
oneStepandtwoStep, where in the first list we remove one element at a time fromlist, and in the second list we remove two elements at a time fromlist. The initial values: the original listlist. - Step 3 (Condition check). If
twoSteportwoStepwithout its head equalssubList, then we returnoneStepas the half. Otherwise, we remove one element fromoneStepand two fromtwoStep.
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:
- Step 1 (Base conditions). In the
searchmethod we "reduce" two lists: the original list and an empty list. - Step 2 (Finding the middle). We find
middle— the middle of these two lists — a list containing half the elements of the original list, using the algorithm above. -
Step 3 (Condition check). Comparison of the key with the head element of
middle.- If the original key is less than the head element of
middle, we continue searching in the left half ("reduce" the original list andmiddle). - If the original key is greater than the head element of
middle, we continue searching in the right half ("reduce"middlewithout its head and an empty list). - If the original key equals the head element of
middle, we return that element.
- If the original key is less than the head element of
- Step 4 (Termination). If during the "reduction" the two lists become equal, the sought element is not found.
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:
- Initialization:
list = List(1, 3, 5, 7, 9), subList = List(),key = 3 -
Finding the half:
oneStep = List(1, 3, 5, 7, 9), twoSteps = List(1, 3, 5, 7, 9) =>oneStep = List(3, 5, 7, 9), twoSteps = List(5, 7, 9) =>oneStep = List(5, 7, 9), twoSteps = List(9), recursion ends:twoStepswithout its head equalssubList- The half is
List(5, 7, 9)
- Condition check:
3is less than5, so we continue for listslist = List(1, 3, 5, 7, 9), subList = List(5, 7, 9). -
Finding the half:
oneStep = List(1, 3, 5, 7, 9), twoSteps = List(1, 3, 5, 7, 9)oneStep = List(3, 5, 7, 9), twoSteps = List(5, 7, 9), recursion ends:twoStepsequalssubList.- The half is
List(3, 5, 7, 9)
- The original key equals the head element of the "half", so we return the answer:
3.
Estimation:
-
Time:
- Worst - \(O(\log n)\)
- Best - \(O(1)\)
- Average - \(O(\log n)\)
- Memory - \(O(1)\)
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: