Searches the specified array of doubles for the specified value using the binary search algorithm. - Java java.lang

Java examples for java.lang:Math Trigonometric Function

Description

Searches the specified array of doubles for the specified value using the binary search algorithm.

Demo Code


//package com.java2s;

public class Main {
    /**//from w  ww  .  j  av  a 2 s.  com
     * Searches the specified array of doubles for the specified value using the
     * binary search algorithm. (this search method has compatibility to Java2
     * (java.util.Arrays)) The array <strong>must</strong> be sorted
     * 
     * @param a
     *            the array to be searched.
     * @param key
     *            the value to be searched for.
     * @return index of the search key, if it is contained in the list;
     *         otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The
     *         <i>insertion point</i> is defined as the point at which the key
     *         would be inserted into the list: the index of the first element
     *         greater than the key, or <tt>list.size()</tt>, if all elements
     *         in the list are less than the specified key. Note that this
     *         guarantees that the return value will be &gt;= 0 if and only if
     *         the key is found.
     */
    public static int binarySearch(double[] d, double key) {
        int low, high, middle;
        int num = d.length;

        low = 0;
        high = num - 1;

        if (d[num - 1] < key)
            return -1 - num;
        if (d[0] > key)
            return -1;
        try {
            while (low <= high) {
                middle = (low + high) / 2;
                if (key == d[middle])
                    return middle;
                if (key > d[middle] && key < d[middle + 1])
                    return -2 - middle;
                else if (key < d[middle])
                    high = middle - 1;
                else
                    low = middle + 1;
            }
        } catch (RuntimeException e) {
        }
        return -1;
    }
}

Related Tutorials