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

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

Description

Perform a binary search on a sorted array a to find the element with the smallest distance 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 greater than or equal to key

Declaration

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

Method Source Code

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

public class Main {
    /**//from   w  w  w  . j a v a2 s  . c om
     * Perform a binary search on a sorted array {@code a} to find the
     * element with the smallest distance to {@code key}. The returned
     * element's value is always greater than or equal to {@code key}.
     *
     * @param a   Array with ascending values
     * @param key Pivot value
     * @return Index of the array element whose value is greater than or equal
     *         to {@code key}
     */
    public static int binarySearchCeil(double[] a, double key) {
        if (a.length == 0) {
            return -1;
        }
        int i = binarySearch(a, key);
        if (i >= 0 && a[i] < key) {
            i++;
        }
        return i;
    }

    /**
     * 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(Object[] a, Object key)
  2. binarySearch(String[] arr, String value)
  3. binarySearch(String[] array, String sought)
  4. binarySearch(T[] a, T x)
  5. binarySearch0(float[] a, int fromIndex, int toIndex, float key)
  6. binarySearchIndex(double[] values, double toFind)
  7. binarySearchLower(int[] theSearchBase, int theLowerBound, int theUpperBound, int theKey)
  8. binarySearchReversed(int[] a, int fromIndex, int toIndex, int key)
  9. binarySearchStringArray(String[] array, String item, int first, int last)