If an ordered array arr is given an element to search for, return the index, or -1 if noneCopy the code

1. Binsearch.java:

package com.yuhl.right;

/ * * *@author yuhl
 * @Date 2020/10/24 21:59
 * @Classname BinSearch
 * @DescriptionBinary search, provided the array is ordered, finds the subscript of the small searched element, and returns -1 */ if none exists
public class BinSearch {
    public static void main(String[] args) {
        int[] arr = {2.4.6.8};
        // non-recursive query
        int index = binSearch(arr, 8);
        System.out.println(index);
        System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
        // recursive query
        int reIndex = reBinSearch(arr, 8.1,arr.length-1);
        System.out.println(reIndex);

    }

    /** * use the branch idea, O(logN) **@paramArray arr *@paramKey Search value *@return* /
    public static int binSearch(int[] arr, int key) {
        int low = 0;
        int high = arr.length - 1;
        int middle = 0;

        if (key < arr[low] || key > arr[high] || low > high) {
            return -1;
        }

        while (low <= high) {
            middle = (low + high) / 2;
            if (arr[middle] > key) {
                high = middle - 1;
            } else if (arr[middle] < key) {
                low = middle + 1;
            } else {
                returnmiddle; }}return -1;
    }

    /** ** *@paramArray arr *@paramKey Search value *@param low
     * @param high
     * @return* /
    public static int reBinSearch(int[] arr, int key, int low, int high) {

        if (key < arr[low] || key > arr[high] || low > high) {
            return -1;
        }

        int middle = (low + high) / 2;            // The initial middle position
        if (arr[middle] > key) {
            If the value is larger than the keyword, the keyword is in the left area
            return reBinSearch(arr, key, low, middle - 1);
        } else if (arr[middle] < key) {
            If the value is smaller than the keyword, the keyword is in the right area
            return reBinSearch(arr, key, middle + 1, high);
        } else {
            returnmiddle; }}}Copy the code

2. Execution Results:

"C: \ Program Files \ Java \ jdk1.8.0 _201 \ bin \ Java exe" 
3= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =3
Copy the code