SultanC
  1. Home
  2. Examples
  3. Algorithms

Binary search in a sorted vector

algorithms/binary_search.sn
def binary_search(values: vector int, needle: int): int {
    let count: uint = length(values) as uint;
    let low: mutable int = 0;
    let high: mutable int = count as int;
    high := high - 1;
    while (low <= high) {
        let distance: int = high - low;
        let mid: int = low + (distance / 2);
        let index: uint = mid as uint;
        let value: int = values[index];
        if (value == needle) { return mid; };
        if (value < needle) {
            low := mid + 1;
        } else {
            high := mid - 1;
        };
    }
    return 0 - 1;
}

def search_case(needle: int): int {
    let values: vector int = [2, 5, 8, 13, 21, 34, 55, 89, 144];
    return binary_search(values, needle);
}

def main(): int {
    return search_case(55);
}

Run it

With the interpreter, without compiling:

./build/sultanc run examples/en/algorithms/binary_search.sn

Or compile it to an executable:

./build/sultanc examples/en/algorithms/binary_search.sn -o build/example && ./build/example

Source on GitHub   All examples