Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.List;

public class Main {
    public static <T1 extends Comparable<T2>, T2> int binarySearch(final List<T2> lst, final T1 elem) {
        if (lst == null || elem == null)
            throw new NullPointerException();

        int low = 0;
        int high = lst.size() - 1;

        while (low <= high) {
            final int mid = low + (high - low) / 2;

            final T2 testElem = lst.get(mid);
            final int comparison = elem.compareTo(testElem);

            if (comparison == 0)
                return mid;
            if (comparison > 0) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        return -(low + 1);
    }
}