0

这是我的二进制搜索程序:

  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;
    }
}}}

输出始终为“找不到元素”。有人可以指出我的错误吗?程序的线性搜索部分还没有完成。提前致谢。

4

2 回答 2

0

您的线路:

j=A[i];

应该:

A[i]=j;

此外,您需要交换以下两行的位置:

low = mid + 1;
up = mid - 1;
于 2013-10-10T03:53:00.583 回答
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;
    }
    }
    }
于 2013-10-10T04:14:53.053 回答