线性和二进制搜索逻辑错误

时间:2014-11-16 06:28:06

标签: java arrays binary-search linear-search

我正在开发一个程序,我必须演示线性和二进制搜索算法的工作原理。为此,我正在加入一个包含20个数字和来自用户的搜索键的数组。代码编译,不会抛出运行时错误。但是,当我在数组中搜索一个数字(例如12)时,而不是打印出在第12位找到的数字,它表示该数字位于第6位:

import java.util.*;
class prg14
{
    int num [] = new int [20];
    int search;

    public void lin (int arr[], int a)
    {
        num = arr;
        search = a;
        int i;
        int flag = 0;

        for (i=0; i<num.length; i++)
        {
            if (search == num[i])
            {
                flag = 1;
                break;
            }

        }
        if (flag == 1)

        { 
            System.out.println("Linear Search : ");
            System.out.println(a+ " found at position " + (i + 1));
        }
        else
        {
            System.out.println("Linear Search : ");
            System.out.print(a+ " not present in the list \n");
        }
    }

    public void binary(int array[], int a)
    {

        int first  = 0;
        int n = 20;
        int last   = n - 1;
        int middle = (first + last)/2;

        while( first <= last )
        {
            if ( array[middle] < search )
                first = middle + 1;    
            else if ( array[middle] == search ) 
            {
                System.out.println("Binary search : ");
                System.out.println(search + " found at position " + (middle+1) + ".");
                break;
            }
            else
                last = middle - 1;

            middle = (first + last)/2;
        }
        if ( first > last )

        {System.out.println("Binary Search : ");
            System.out.println(search + " not present in the list.\n");
        }
    }   


    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        prg14 obj = new prg14();
        System.out.println("Enter any 20 numbers.");
        String str;
        int linn[] = new int[20];
        int i;
        for( i = 0; i<10; i++)
        {
            str = sc.next();
            linn[i] = sc.nextInt();
        }
        System.out.println("Enter number to be searched.");
        int search = sc.nextInt();
        obj.lin(linn, search);
        obj.binary(linn, search);

    }

}

如何解决此问题? TIA。

1 个答案:

答案 0 :(得分:1)

删除String str,例如

for( i = 0; i<linn.length; i++)
{
   // str = sc.next();
   linn[i] = sc.nextInt();
}

您没有混合行输入和标记化输入,因此您不必担心尾随换行符(在本例中)。另外,我将通过返回匹配的索引(如果没有找到,则为-1)来实现线性搜索功能

public static int linear(int arr[], int a) {
    for (int pos = 0; pos < arr.length; pos++) {
        if (arr[pos] == a) {
            return pos;
        }
    }
    return -1;
}

我会对binarySearch做同样的事情。这样您就可以将消息显示与计算分开。