/// Returns the index of target in a SORTED array, or -1 if it is absent.
int binarySearch(int[] items, int target) {
    int low = 0;
    int high = items.length - 1;

    while (low <= high) {
        int middle = (low + high) / 2;

        if (items[middle] == target) {
            return middle;
        } else if (items[middle] < target) {
            low = middle + 1;
        } else {
            high = middle - 1;
        }
    }

    return -1;
}

void main() {
    int[] numbers = {4, 8, 9, 15, 17, 23, 42};

    IO.println(binarySearch(numbers, 42));
    IO.println(binarySearch(numbers, 4));
    IO.println(binarySearch(numbers, 99));
}

// From Groundwork, chapter 11 (ch11-searching-and-sorting), box 2.
// This example is from Groundwork, licensed CC BY-NC-SA 4.0.
// Run with: java ch11_02.java
