这是我的二元搜索程序:
import java.io.*;
public class Program14
{
public void ArraySearching()throws IOException
{ BufferedReader br=new BufferedReader( new InputStreamReader(System.in));
int A[]=new int[15];
System.out.println("Input an array of 15 elements in descending order");
for(int i=0;i<15;i++)
{
int j=Integer.parseInt(br.readLine());
j=A[i];
}
System.out.println("Input the number to be searched");
int n=Integer.parseInt(br.readLine());
System.out.println("Press 1 for Binary search");
System.out.println("Press 2 for linear search");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
{
int flag=0,low,up,mid=0;
low=0;
up=14;
while(low<=up)
{
mid=(low+up)/2;
if(n>A[mid])
low=mid+1;
else if(n<A[mid])
up=mid-1;
else
{flag=1;
break;
}
}
if(flag==1)
System.out.println("Element at position"+(mid+1));
else
System.out.println("Element not found");
break;
}
}}}
输出始终为“未找到元素”。有人可以指出我的错误吗?该程序的线性搜索部分尚未完成。提前致谢。
答案 0 :(得分:0)
你的专栏:
j=A[i];
应该是:
A[i]=j;
此外,您需要交换以下两行的位置:
low = mid + 1;
up = mid - 1;
答案 1 :(得分:0)
public static void main(String[] args) throws IOException
{ BufferedReader br=new BufferedReader( new InputStreamReader(System.in));
int A[]=new int[15];
System.out.println("Input an array of 15 elements in descending order");
for(int i=0;i<15;i++)
{
int j=Integer.parseInt(br.readLine());
A[i]=j;
}
System.out.println("Input the number to be searched");
int n=Integer.parseInt(br.readLine());
System.out.println("Press 1 for Binary search");
System.out.println("Press 2 for linear search");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
{
int flag=0,low,up,mid=0;
low=0;
up=14;
int count = 0;
mid=(low+up)/2;
while(low<=up)
{
if(n>A[mid]){
mid--;
}
else if(n<A[mid]){
mid++;
}
else
{
flag=1;
break;
}
count++;
}
System.out.println(count);
if(flag==1)
System.out.println("Element at position"+(mid+1));
else
System.out.println("Element not found");
break;
}
}
}