线性搜索技术

时间:2017-03-29 20:04:24

标签: java algorithm linear-search

我正在编写一个程序,读取包含N行N列整数的方阵的文件。文件的第一行包含一个值,用于指定网格其余部分的N的“大小”。例如,如果第一行包含“10”,则其余行形成10×10矩阵。我的程序应该显示通过使用“强力”线性技术O(N ^ 2)找到(或找不到)给定元素所需的比较总数。 示例c:\ temp \ input.txt:

10

1 5 8 13 16 18 22 23 28 29

6 9 14 19 20 22 23 27 33 34

11 14 15 20 24 26 27 31 34 39

16 21 23 28 30 34 35 36 39 44

17 25 26 32 36 41 43 47 49 53

19 28 30 35 40 43 44 49 53 56

23 31 33 38 43 48 52 58 60 61

27 34 35 41 44 52 55 59 61 65

29 38 40 44 45 54 60 65 66 67

33 41 46 47 51 59 61 69 70 80

示例(作为Java App):

java program.class c:\ temp \ infile.txt 59

使用线性搜索在68次比较中发现了

58

这是我的代码

   public static int[][] create2DIntMatrixFromFile(String filename) throws Exception {

    int[][] matrix = null;
    String line;
    int size = buffer.read();
    int row=0;
    while ((line = buffer.readLine()) != null) {
    String[] vals = line.trim().split("\\s+");
    if (matrix == null) {
    public static void main(String[] args)
    {
    BufferedReader buffer = new BufferedReader(new FileReader(args[0]));
    int size = buffer.read();
    int[][] matrix = new int[100][100];
    matrix = create2DIntMatrixFromFile(args[0]);
    search1(matrix, size,args[1]);
    matrix = new int[size][size];
    }
    for (int col = 0; col < size; col++) {
    matrix[row][col] = Integer.parseInt(vals[col]);
     }
    }
    row++;
    }
    return matrix;
    }
    void search1(int [][]matrix,int size,int x)
    {
    int count=0,comp=0;
    for(int i=0;i<size;i++)
    { for(int j=0;j<=size;j++)
    if(matrix[i][j]==x) count++;
    comp++;
    }
    System.out.println(count+" found in" + comp + "comparisons using a linear search");
     }

问题是我在主要方法上一直遇到语法错误,即search1方法不正确,我无法修复它。我欣赏的任何帮助

1 个答案:

答案 0 :(得分:0)

你应该做的第一件事就是提供格式良好的代码。从我能够理解你的问题可能是你从静态main调用非静态方法,所以要么使search1静态或从类构造函数调用它(你需要创建一个)。

相关问题