日期:2014-05-20  浏览次数:20768 次

大神帮我看看这个小的查找,哪里出错了?
public class Search{
public static void main(String [] args) {
int a[] = {1, 3, 4, 7, 9, 20, 58, 79 };
int i = 9;
System.out.println(twofen(a,i));

}
public static int twofen(int []a,int num) {
if(a.length == 0)return -1;
int firstpos = 0;
int lastpos = a.length -1;
int m = (firstpos + lastpos) / 2;
while(firstpos <= lastpos){
if(num == a[m])return m;
if(num < a[m]){lastpos = a[m]-1;}
if(num > a[m]){firstpos = a[m]+1;}
m = (firstpos + lastpos) / 2;
}
return -1;
}

------解决方案--------------------
你明显那个部分if没有返回值
while(firstpos <= lastpos){
if(num == a[m])return m;
if(num < a[m]){lastpos = (m-1)/2;}
if(num > a[m]){firstpos = (m+1)/2;}
m = (firstpos + lastpos) / 2;
return -1;
}
修改成
while(firstpos <= lastpos){
if(num == a[m])return m;
if(num < a[m]){lastpos = (m-1)/2;}
if(num > a[m]){firstpos = (m+1)/2;}
m = (firstpos + lastpos) / 2;
return m;}
}
return -1;
}

------解决方案--------------------
刚才那个有点小错误,重发个:
Java code

public class Search{
public static void main(String [] args) {
int a[] = {1, 3, 4, 7, 9, 20, 58, 79 };
int i = -1;
System.out.println(twofen(a,i));
}  

public static int twofen(int []a,int num) {
if(a.length == 0)return -1;
int firstpos = 0;
int lastpos = a.length -1;
while(firstpos <=lastpos){
if(num == a[(firstpos + lastpos) / 2])return (firstpos + lastpos) / 2;
if(num < a[(firstpos + lastpos) / 2]){lastpos = ((firstpos + lastpos) / 2)-1;}
if(num > a[(firstpos + lastpos) / 2]){firstpos = ((firstpos + lastpos) / 2)+1;}

}
return -1;
}
}

------解决方案--------------------
将if(num < a[m]){
lastpos = a[m]-1;
}
if(num > a[m]){
firstpos = a[m]+1;
}两名改为:
if(num < a[m]){
lastpos = m-1;
}
if(num > a[m]){
firstpos = m+1;
}


------解决方案--------------------
还有你好像多了一个大括号
------解决方案--------------------
1,“int twofen(int []a,int num)”应将此函数应放在class Search里,而不是外面
2,“if(num < a[m]){lastpos = a[m]-1;}”须将 a[m]-1改为m-1
及“if(num > a[m]){firstpos = a[m]+1;}“里的a[m]+1改为m+1即可
------解决方案--------------------
Java code
public class Search{
    public static void main(String [] args) {
        int a[] = {1, 3, 4, 7, 9, 20, 58, 79 };
        int i = 9;
        System.out.println(twofen(a,i));
    }  
    public static int twofen(int []a,int num) {
        if(a.length == 0) return -1;
        int firstpos = 0;
        int lastpos = a.length -1;
        int m = (firstpos + lastpos) / 2;
        while(firstpos <= lastpos){
            if(num == a[m]) return m;
            if(num < a[m]){    lastpos = m-1;}
            if(num > a[m]){    firstpos = m+1;}
            m = (firstpos + lastpos) / 2;
        }
        return -1;
    }
}