Java Binary Search binarySearch(double[] arr, double value, int p, int q)

Here you can find the source of binarySearch(double[] arr, double value, int p, int q)

Description

Add by Chuan binary search

License

Open Source License

Parameter

Parameter Description
arr sorted array to be searched
value target search value
p begin index
q end index

Return

the biggest index b such that arr[b]Declaration
public static int binarySearch(double[] arr, double value, int p, int q) 

Method Source Code

//package com.java2s;
/*/*from www. j a va 2 s .c o m*/
Copyright (c) 2014 cs.nmsu.edu
    
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
    
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
    
The Software shall be used for Good, not Evil.
    
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

public class Main {
    /**
     * Add by Chuan
     * binary search
     * @param arr sorted array to be searched
     * @param value target search value
     * @param p begin index
     * @param q end index
     * @return the biggest index b such that arr[b]<value; -1 if value < arr[0]
     */
    public static int binarySearch(double[] arr, double value, int p, int q) {
        if (p > q)
            return p - 1;

        int r = (p + q) / 2;
        if (arr[r] == value)
            return r;
        else if (arr[r] < value)
            return binarySearch(arr, value, r + 1, q);
        else
            return binarySearch(arr, value, p, r - 1);
    }
}

Related

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