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
Related
larzalgoClassic sorting/searching algorithms that record every comparison and swap→FizzBuzz in LarzscriptThe classic interview warm-up: print 1 to N, but Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both.→Reverse a String in LarzscriptFlip a string end to end - one of the smallest real string algorithms, and a good first look at the str package.→Check if a String is a Palindrome in LarzscriptDetect whether a string reads the same forwards and backwards, ignoring case, spaces and punctuation.→