I am looking for a bisect
operation in Haskell similar to Python's bisect_left()
and friends. The input would be a lower bound, an upper bound, a non-decreasing function (Ord a)=>(Int->a) which must be defined for all integers between the lower and upper bound, and a search value. The return value is the highest integer i
where lower <= i <= upper
and f(i) < search_term
. Performance should be O(log(n)).
Hoogling for this:
(Ord a)=>(Int->a)->Int->Int->a->Int
does not yield any results.
Is there a standard, generic binary search operator in a library somewhere?
What is Bisection/Binary Search? Binary Search or Bisection Search or Logarithmic Search is a search algorithm that finds the position/index of an element within a sorted search list.
Basically, this module implements bisection algorithms to find the insertion point for adding a given element in a sorted list. It is worth mentioning that list passed as an argument to these functions must be sorted in ascending order, if not the functions will not launch any error but the result will be unexpected.
Practical Data Science using PythonThe bisect is used for binary search. The binary search technique is used to find elements in sorted list. The bisect is one library function.
The purpose of Bisect algorithm is to find a position in list where an element needs to be inserted to keep the list sorted. Python in its definition provides the bisect algorithms using the module “bisect” which allows to keep the list in sorted order after the insertion of each element.
Ross Paterson's binary-search package on Hackage does what you're looking for. Specifically, see searchFromTo, which has type signature
searchFromTo :: Integral a => (a -> Bool) -> a -> a -> Maybe a
As Tikhon points out, [a]
in Haskell is a linked list rather than an array. Since linked lists only support sequential access, it is not possible to get a logarithmic-time search on an [a]
data structure. Instead, you should use a genuine array data structure -- see the vector library for the preferred implementation of arrays.
Dan Doel has written a family of binary search functions for the mutable vectors in the vector package: see Data.Vector.Algorithms.Search in his vector-algorithms library. In contrast to Ross Paterson's library, which provides a pure API, the API in Data.Vector.Algorithms.Search
is monadic (that is, it must be run in the ST
monad or the IO
monad).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With