#!/usr/bin/ruby

# Translation of: http://rosettacode.org/wiki/Binary_search#Perl

func binary_search(array, value, low, high) {
    high < low && return -1;
    var middle = (high+low / 2 -> int);

    if (value < array[middle]) {
        return binary_search(array, value, low, middle-1);
    }
    elsif (value > array[middle]) {
        return binary_search(array, value, middle+1, high);
    }

    return middle;
}

var arr = [
    0,
    3,
    5,
    7,
    8,
    12,
    15,
    23,
    55,
    75,
    122,
    345,
    553,
    676,
    883,
    997,
];

[15, 120, 122, 532, 1235, 8, 0, 12425, 997, 325].each { |value|
    var idx = binary_search(arr, value, 0, arr.end);

    arr.contains(value) == (idx != -1) ||
        "Error on value: %d\n".sprintf(value).die;

    "%20s -> %2s\n".printf(value, idx);
}
