Java Array Search search(double[] input, int[] bounds, double x)

Here you can find the source of search(double[] input, int[] bounds, double x)

Description

Recursive binary search.

License

Open Source License

Parameter

Parameter Description
input is an array in which to search
bounds is a length 2 int array of indices between which to search
x is the value to find

Return

the indices of the elements that bracket x. The indices are identical if an exact match is found. {-1,-2} means not found.

Declaration

public static int[] search(double[] input, int[] bounds, double x) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from w ww .  ja  v  a 2  s .  com*/
     * Recursive binary search.  Finds the indices that bracket the provided value.
     * If an exact match is found, that index is returned in both spots.
     * Returns negative indices if not found.  Sorted X, ascending or descending.
     * See also java.util.Arrays.
     * 
     * @param input is an array in which to search
     * @param bounds is a length 2 int array of indices between which to search
     * @param x is the value to find
     * @return the indices of the elements that bracket x.  The indices are identical if an exact match is found.  {-1,-2} means not found. 
     */
    public static int[] search(double[] input, int[] bounds, double x) {
        // called on same index
        if (bounds[0] == bounds[1]) {
            return new int[] { bounds[0], bounds[1] };
        }
        // in between the two indices
        if (bounds[1] - bounds[0] == 1) {
            return new int[] { bounds[0], bounds[1] };
        }
        // exact match to one of the indices
        if (input[bounds[0]] == x) {
            return new int[] { bounds[0], bounds[0] };
        }
        if (input[bounds[1]] == x) {
            return new int[] { bounds[1], bounds[1] };
        }
        // otherwise, keep going
        int mid = (bounds[0] + bounds[1]) / 2;
        if ((x >= input[mid] && x < input[bounds[1]]) || (x <= input[mid] && x > input[bounds[1]])) {
            return search(input, new int[] { mid, bounds[1] }, x);
        }
        if ((x <= input[mid] && x > input[bounds[0]]) || (x >= input[mid] && x < input[bounds[0]])) {
            return search(input, new int[] { bounds[0], mid }, x);
        }
        // error condition
        return new int[] { -1, -2 };
    }
}

Related

  1. isInArray(String needle, String[] haystack)
  2. memchr(boolean[] ary, int start, int len, boolean find)
  3. memchr(char[] haystack, int offset, char needle, int num)
  4. memchr(T[] ptr, T value)
  5. replaceAll(String text, char[] toSearch, char toReplace)
  6. Search(int[] in, int val)
  7. searchFirst(String[] target, String key)
  8. searchInStringArray(String key, String[] data)