求解,这个二分查找法有什么不对的地方
package half;
import java.util.*;
public class erfenchazhaofa {
public static void main(String[] args)
{
int length,i;
int a[];
Scanner in = new Scanner(System.in);
System.out.println("请输入数组长度:");
length = in.nextInt();
a= new int[length];
for (i = 0; i < length; i++) {
System.out.print("输入第" + (i + 1) + "个数据");
a[i] = in.nextInt();
}
System.out.println("请输入要查找的数:");
int find=in.nextInt();
int result=search(a,length,find);
System.out.println("要查找的数字"+find+"是第"+result+"个数字");
}
public static int search(int a[],int n,int x){
int head=0;
int tail=n-1;
int mid=(head+tail)/2;
while(head<=tail)
{
if(a[mid]==x)
{
return mid;
}
else if(a[mid]>x)
{
tail=mid-1;
}
else if(a[mid]<x)
{
head=mid+1;
}
}
return mid-1;
}
}
------解决方案--------------------亲,你的程序确实有错误!
int mid=(head+tail)/2;把这句放到while循环里面就ok了!
while(head<=tail)
{
int mid=(head+tail)/2;
if(a[mid]==x)