dequanth

导航

递归方法解决二分法

要求:

  • 客户甲随机输入一个给定长度的整数型数组,且不论客户输入数字的顺序如何,都将数组的值自动从小到大排序。
  • 利用二分法查找客户乙给定的数值是否存在于客户甲给定的数组当中,如果存在则给定位置。
import java.util.Scanner;
//客户甲随机输入一个给定长度的整数型数组,且不论客户输入数字的顺序如何,都将数组的值自动从小到大排序。
//利用二分法查找客户乙给定的数值是否存在于客户甲给定的数组当中,如果存在则给定位置
public class BinarySearch {
    public static void main(String[] args) {
        //客户甲给定一个整数型数组
        int[] input = new int[4];
        Scanner scanner = new Scanner(System.in);
        System.out.println("请给数组随机赋值!一共4个数值");
        for (int i = 0; i < 4; i++) {
            input[i]=scanner.nextInt();
        }
        //利用冒泡法给数组排序
        for (int i = 0; i < input.length; i++) {
            boolean flag=true;
            for (int j = 0; j < input.length-i-1; j++) {
                if(input[j]>input[j+1]){
                    int temp = input[j];
                    input[j] = input[j+1];
                    input[j+1] = temp;
                    flag=false;
                }
            }
            if(flag){
                break;
            }
        }
        System.out.println("请客户随机给定一个整数:");
        int ran = scanner.nextInt();
        int loc = binarySear(0,ran,input);
        if(loc==-1){
            System.out.println("客户指定的数字不在数组当中!");
        }else{
            System.out.println("客户指定的数字在数组当中,是第"+(loc+1)+"位!");
        }
        //打印数组
        for (int i : input) {
            System.out.print(i+"\t");
        }
    }

    public static int binarySear(int loc,int tar,int[] group){
        int key = group.length/2;
        if(tar == group[0]){
            return 0+loc;
        }else if(tar==group[group.length-1]){
            return loc+group.length-1;
        }else if(tar==group[key]){
                return loc+key;
        }else if(key==1){
            return -1;
        }else if(tar<group[key]){
            int[] groupp = new int[key];
            for (int i = 0; i < key; i++) {
                groupp[i]=group[i];
            }
            loc=binarySear(loc,tar,groupp);
            return loc;
        }else {
            int[] groupp = new int[key];
            for (int i = 0; i < key; i++) {
                groupp[i]=group[key+i];
            }
            if(binarySear(loc,tar,groupp)==-1){
                return -1;
            }else{
                loc=binarySear(loc,tar,groupp)+key;
                return loc;
            }
        }
    }
}

posted on 2022-09-21 19:31  dequantianhe  阅读(14)  评论(0编辑  收藏  举报