Java的递归二进制搜索抛出越界异常的了呢? [英] Java recursive binary search throwing out of bounds exception?

查看:124
本文介绍了Java的递归二进制搜索抛出越界异常的了呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我被要求写在我大学的数据结构类递归二进制搜索,但我有一个小问题。当我搜索一个数字,出界(10在这种情况下),它抛出一个越界异常。我理解为什么它这样做,由于没有> 10位的数组,但我不知道如何解决它。有任何想法吗?

该阵列,即时通讯搜索是一个有序阵列1 ​​ - 10(指数0 - 9)。

 公众诠释recursiveBinarySearch(INT [] anArray,INT searchedNumber,INT分钟,INT最大){    如果(分>最大)
        {
                的System.out.println(searchedNumber +不是塔数组present。);
                //返回-1表明该值尚未发现
        返回-1;
        }
        //找到该阵列的中心
        INT中心=(分+最大)/ 2;    如果(anArray [心] == searchedNumber)
        {
                的System.out.println(searchedNumber + +中心是在索引中找到);
        返回中心;
        }        如果(anArray [心]< searchedNumber)
        {
        返回recursiveBinarySearch(anArray,searchedNumber,中心+ 1,最大值);
        }        返回recursiveBinarySearch(anArray,searchedNumber,分,中心-1); }


解决方案

 公众诠释recursiveBinarySearch(...){
    IF(MAX> = array.length){
        最大= array.length - 1;
    }
    如果(分钟< 0){
        分= 0;
    }
    ...在code休息
}

PS不是一个nagger,但我也建议使用一致的缩进。相信我,它写没有bug的程序帮助很大。

Hey, I have been asked to write a recursive binary search for my data structure class in university, but i'm having a slight problem. When i search for a number that is out of bounds (over 10 in this case) it throws an out of bounds exception. I understand why it's doing it, due to the array not having >10 spaces, but i don't know how to work around it. Any ideas?

The array that im searching is an ordered array 1 - 10 (index 0 - 9).

 public int recursiveBinarySearch(int[] anArray, int searchedNumber, int min, int max) {

    if (min > max)
        {
                System.out.println(searchedNumber + " is not present in tha array.");
                //return -1 to show that the value has not been found
        return -1;
        }
        // find the centre of the array
        int centre = (min + max) / 2;

    if (anArray[centre] == searchedNumber)
        {
                System.out.println(searchedNumber + " was found at index " + centre);
        return centre;
        }

        if (anArray[centre] < searchedNumber)
        {
        return recursiveBinarySearch(anArray, searchedNumber, centre+1, max);
        }

        return recursiveBinarySearch(anArray, searchedNumber, min, centre-1);

 }

解决方案

public int recursiveBinarySearch(...) {
    if (max >= array.length) {
        max = array.length - 1;
    }
    if (min < 0) {
        min = 0;
    }
    ... rest of the code
} 

PS Not to be a nagger, but I would also recommend using consistent indentation. Believe me, it helps greatly in writing bug-free programs.

这篇关于Java的递归二进制搜索抛出越界异常的了呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆