Java Binary Search binarySearch(double[] a, double key)

Here you can find the source of binarySearch(double[] a, double key)

Description

Perform a binary search on a sorted array a to find the element with the nearest element to key .

License

Open Source License

Parameter

Parameter Description
a Array with ascending values
key Pivot value

Return

Index of the array element whose value is nearly or exactly key

Declaration

public static int binarySearch(double[] a, double key) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from  ww  w.j a  va 2 s  . co  m
     * Perform a binary search on a sorted array {@code a} to find the
     * element with the nearest element to {@code key}.
     *
     * @param a   Array with ascending values
     * @param key Pivot value
     * @return Index of the array element whose value is nearly or exactly
     *         {@code key}
     */
    public static int binarySearch(double[] a, double key) {
        int l = 0;
        int h = a.length - 1;
        int i;
        do {
            i = (int) (((long) l + (long) h) / 2L);
            if (key > a[i]) {
                l = i + 1;
            } else if (key < a[i]) {
                h = i - 1;
            } else {
                return i;
            }
        } while (l <= h);
        return i;
    }
}

Related

  1. binarySearch(byte[] a, int key)
  2. binarySearch(byte[] readBuffer, int offset, int length, byte value)
  3. binarySearch(char[] arr, int key)
  4. binarySearch(double experience, int min, int max)
  5. binarySearch(double values[], double search)
  6. binarySearch(double[] arr, double value, int p, int q)
  7. binarySearch(final double[] array, final double val)
  8. binarySearch(final Enum[] full, final int[] partial, final char key, final int index)
  9. binarySearch(final Object[] a, final int fromIndex, final int toIndex, final Object key)