日期:2014-05-20 浏览次数:20954 次
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即可
------解决方案--------------------
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;
}
}