集册 Java实例教程 递归二进制搜索法

递归二进制搜索法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

570
递归二进制搜索法
/**来 自 nowjava.com**/

//package com.nowjava;


public class Main {

    /**

     * Recursive binary search method

     * @param items The array being searched

     * @param target The object being searched for

     * @param first The subscript of the first element

     * @param last The subscript of the last element

     * @return The subscript of target if found; otherwise -1.

     */

    private static int binarySearch(Object[] items,

            Comparable<Object> target, int first, int last) {

        if (first > last) {

            return -1; // Base case for unsuccessful search.

        } else {

            int middle = (first + last) / 2; // Next probe index.

            int compResult = target.compareTo(items[middle]);

            if (compResult == 0) {

                return middle; // Base case for successful search.

            } else if (compResult < 0) {//from 时   代    Java - nowjava.com

                return binarySearch(items, target, first, middle - 1);

            } else {

                return binarySearch(items, target, middle + 1, last);

            }

        }

    }


    
展开阅读全文