欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

*用递归写个二分查找;*

程序员文章站 2024-03-17 23:18:28
...

用递归写个二分查找;

package CL6;

import java.util.Scanner;

/**
 * @author: 贾兴伟
 * @date: Created in 20:00 2020/9/22
 */
public class BinarySearch {
    public static int BinarySearched(int[] arr,int beginIndex,int endIndex,int value){
//        int left = beginIndex,right = endIndex,might;
//        while(left<=right) {
//            might=((right-left)>>>2)+left;
//            if (arr[might] < value) {
//                left = might + 1;
//            }else if (arr[might] > value) {
//                right = might - 1;
//            }else {
//                return might;
//            }
//        }
//        return -1;
        int mid = ((endIndex-beginIndex)>>>1)+beginIndex;
        if(beginIndex>endIndex){
            return  -1;
        }
        if(arr[mid]==value){
            return mid;
        }else if(arr[mid]>value){
            return BinarySearched(arr,beginIndex,mid-1,value);
        }else {
            return BinarySearched(arr, mid + 1, endIndex, value);
        }
    }

    public static void main(String[] args) {
        int[] arr = {1,3,5,7,8,9};
        System.out.println("请输入一个数字");
        Scanner scanner = new Scanner(System.in);
        int value= scanner.nextInt();
        int a =BinarySearched(arr,0,arr.length-1,value);
        System.out.println(a);
    }
}
相关标签: java