Searches the specified array of vectors 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 vectors for the specified value using the binary search algorithm.

Demo Code


import java.util.ArrayList;
import java.util.Random;

public class Main{
    /**/*  ww  w  .  j  a  v  a  2s . co m*/
     * Searches the specified array of vectors 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 colm
     *            column number in the vector.
     * @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 binarySearchN(MathVector[] d, double key, int colm) {
        int low, high, middle;
        int num = d.length;

        low = 0;
        high = num - 1;

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

Related Tutorials