Other Python solutions.
from typing import List
def find(search_list: List[int], value: int) -> int:
if len(search_list) == 0:
raise ValueError("value not in array")
index = len(search_list) // 2
middle_item = search_list[index]
if middle_item > value:
return find(search_list[0:index], value)
elif middle_item < value:
return index + 1 + find(search_list[index + 1:], value)
return index
Other Clojure solutions.
(ns binary-search)
(defn middle [coll]
(quot (count coll) 2))
(defn search-for [item coll]
(let [idx (middle coll)
middle-value (nth coll idx)
not-found-error (Exception. "not found")]
(cond
(= item middle-value) idx
(= 1 (count coll)) (throw not-found-error)
(< item middle-value) (search-for item (take idx coll))
:else (+ idx (search-for item (drop idx coll))))))
Other Elm solutions.
module BinarySearch exposing (find)
import Array exposing (Array)
find : Int -> Array Int -> Maybe Int
find target xs =
let
len =
Array.length xs
index =
len // 2
val =
Array.get index xs
in
Maybe.andThen
(\n ->
if n == target then
Just index
else if len == 1 then
Nothing
else if target < n then
find target (Array.slice 0 index xs)
else
Maybe.map ((+) index) <|
find
target
(Array.slice index len xs)
)
val
Other Roc solutions.
module [find]
find : List U64, U64 -> Result U64 _
find = \array, target ->
when array is
[] -> Err NotPresent
[only] -> if only == target then Ok 0 else Err NotPresent
items ->
pivot = List.len items // 2
guess = List.get items pivot
when guess is
Ok x if x == target ->
Ok pivot
Ok x if x > target ->
cutoff = List.len items - pivot
xs = List.dropLast items cutoff
find xs target
Ok _ ->
xs = List.dropFirst items pivot
Result.map (find xs target) (\i -> i + pivot)
Err OutOfBounds -> crash "The pivot point $(Num.toStr pivot) should never be out of bounds for list of length $(Num.toStr (List.len array))."