Algorithms · real, tested code

Binary Search in Larzscript

Find a value in a sorted list in O(log n) instead of scanning every element.

algo.binary_search() returns the found index, or -1 - the real halving-the-search-space algorithm, not a linear fallback in disguise.

larzscript pkg install algo

Code

import "algo" as algo

let xs = [1, 2, 4, 5, 8, 9, 13, 21]
print(algo.binary_search(xs, 8))
print(algo.binary_search(xs, 6))
Output
4
-1