实现简单二进制搜索时出错 [英] Getting error while implementing simple binary search

查看:66
本文介绍了实现简单二进制搜索时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计们

我是java代码的新手,我在编写这个方法时遇到了麻烦:

Hey guys
i'm new to java code and i'm having trouble with this method i wrote :

/** BinarySearchRecursive
	 * 
	 * @param name = to search
	 * @param l = left index
	 * @param r = right index
	 * @param m = middle index
	 */
	public int Binary_search( String name, int l , int r )
	{
		int lenForSearch = name.length();
		
		if( name.compareToIgnoreCase(AddBook.get(l).get_fname().substring(0,lenForSearch)) == 0 )//found contact's index
		{
			return l;
		}
		else if( l == r )return -1;//contact was not found
		
		int  m = ( (l+r)/2 );
		
		if( name.compareToIgnoreCase(AddBook.get(m).get_fname().substring(0,lenForSearch)) > 0 )//name < AddBook[m]
		{
			 return Binary_search( name, l , m );
		}
		
		else Binary_search( name, m , r );//name > AddBook[m]
	}



错误是关于返回语句问题,我找不到问题所在。

ERROR此方法必须返回int类型的结果

请指导我(:


the error is about a return statements issue and i can't find where is the problem.
the ERROR " This method must return a result of type int "
please guide me (:

推荐答案

可能这个将为你工作:

Probably this will work for you:
/** BinarySearchRecursive
     *
     * @param name = to search
     * @param l = left index
     * @param r = right index
     * @param m = middle index
     */
    public int Binary_search( String name, int l , int r )
    {
        int lenForSearch = name.length();

        if( name.compareToIgnoreCase(AddBook.get(l).get_fname().substring(0,lenForSearch)) == 0 )//found contact's index
        {
            return l;
        }
        else if( l == r )return -1;//contact was not found

        int  m = ( (l+r)/2 );

        if( name.compareToIgnoreCase(AddBook.get(m).get_fname().substring(0,lenForSearch)) > 0 )//name < AddBook[m]
        {
             return Binary_search( name, l , m );
        }

        //here you have missed the return statement
        else return Binary_search( name, m , r );//name > AddBook[m]
    }





你错过了最后一种情况下的return语句。在每种情况下,如果将整数设置为函数的返回类型,代码必须返回一个整数值。



You've missed the return statement in the last case. In every case the code has to return an integer value if you set an integer to the return type for your function.


这篇关于实现简单二进制搜索时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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