Here you can find the source of search(double[] input, int[] bounds, double x)
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 |
public static int[] search(double[] input, int[] bounds, double x)
//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 }; } }