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

递归二进制搜索

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

550
检查一个排序数组中是否存在一个整数(key),并返回密钥的索引(如果找到)和-1(如果没有找到)
//N o w J a v a . c o m - 时  代  Java



import java.util.*;

public class Binary_recursive{

    private int size;

    private int[] arr;

    private int key;


    private int search( int min, int max )

    {

        int mid;

        if ( min <= max ) {

            mid = middle( min, max );

            if( this.arr[mid] == this.key ){

                return mid;

            }

            else if ( this.arr[mid] < this.key ) {

                min = mid + 1;

                return this.search( min, max );// 来 自 N o w  J a v a  .   c o m

            }

            else{

                max = mid - 1;

                return this.search( min, max );

            }

        }

        return -1;

    }


    private int middle( int min, int max )

    {

        int sum = min + max; 

        if ( sum%2 == 0 )

        {

            return sum/2;

        }

        else

        {

            return (sum/2)+1;

        }

    }


    public static void main(String[] args)

    {

        Scanner in = new Scanner(System.in);

        int i,result;

        

        Binary_recursive InputArray = new Binary_recursive();

    

        System.out.print("Size of array = ");

        InputArray.size = in.nextInt();


        InputArray.arr = new int[InputArray.size];


        System.out.println("Enter the integers in the array : ");

        for ( i=0; i<InputArray.size; i++ ) {

            InputArray.arr[i] = in.nextInt();

        }


        System.out.print("Enter the integer to be searched : ");

        InputArray.key = in.nextInt();


        result = 
展开阅读全文