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

实现递归二进制搜索

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

571
实现递归二进制搜索

import java.util.*;

import java.util.stream.Collectors;
/** 来 自 时代Java - nowjava.com**/


public class ImplementRecursiveBinarySearch {


    public static void main(String[] args) {


        Scanner scn = new Scanner(System.in);

        int searchedElement = scn.nextInt();

        scn.nextLine();

        String[] inputLine = scn.nextLine().split(" ");

        int size = inputLine.length;

        int[] numbers = new int[size];

        for (int i = 0; i < size; i++) {

            numbers[i] = Integer.parseInt(inputLine[i]);

        }

        System.out.println(binarySearch(numbers,searchedElement));

    }


    public static int binarySearch(int[] a, int target) {/*时代Java公众号 - nowjava.com 提供*/

        return binarySearch(a, 0, a.length-1, target);

    }


    public static int binarySearch(int[] a, int start, int end, int target) {

        int middle = (start + end) / 2;

        if(end < start) {

            return -1;

        }


        if(target==a[middle]) {

            
展开阅读全文