在字符串数组上实现二进制搜索

时间:2015-08-27 22:27:10

标签: java binary-search

我遇到了一些麻烦。输入数组基于文件输入,数组的大小由文件中的第一行指定。 binarySearch方法看起来似乎没问题,但它似乎没有用。有人能帮忙吗?感谢。

public static int binarySearch(String[] a, String x) {
    int low = 0;
    int high = a.length - 1;
    int mid;

    while (low <= high) {
        mid = (low + high) / 2;

        if (a[mid].compareTo(x) < 0) {
            low = mid + 1;
        } else if (a[mid].compareTo(x) > 0) {
            high = mid - 1;
        } else {
            return mid;
        }
    }

    return -1;
}

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Enter the name of your file (including file extension): ");
    String filename = input.next();

    String[] numArray;
    try (Scanner in = new Scanner(new File(filename))) {
        int count = in.nextInt();

        numArray = new String[count];

        for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
            numArray[i] = in.nextLine();
        }

        for (int i = 0; i < count; i++) //printing all the elements
        {
            System.out.println(numArray[i]);
        }

        String searchItem = "The";

        System.out.println("The position of the String is:");
        binarySearch(numArray, searchItem);

    } catch (final FileNotFoundException e) {
        System.out.println("That file was not found. Program terminating...");
        e.printStackTrace();

    }

}

5 个答案:

答案 0 :(得分:7)

我添加了以下示例以供您进一步了解。

import java.util.Arrays;

public class BinaryStringSearch {

    public static void main(String[] args) {

        String array[] ={"EWRSFSFSFSB","BB","AA","SDFSFJ","WRTG","FF","ERF","FED","TGH"};
        String search = "BB";

        Arrays.sort(array);

        int searchIndex = binarySearch(array,search);

        System.out.println(searchIndex != -1 ? array[searchIndex]+ " - Index is "+searchIndex : "Not found");
    }

    public static int binarySearch(String[] a, String x) {
        int low = 0;
        int high = a.length - 1;
        int mid;

        while (low <= high) {
            mid = (low + high) / 2;

            if (a[mid].compareTo(x) < 0) {
                low = mid + 1;
            } else if (a[mid].compareTo(x) > 0) {
                high = mid - 1;
            } else {
                return mid;
            }
        }

        return -1;
    }

}

答案 1 :(得分:1)

我希望它会有所帮助:

 public static void main(String ar[]){

    String str[] = {"account","angel","apple","application","black"};
    String search= "application";
    int length = str.length-1;
    BinarySearchInString findStrin = new BinarySearchInString();
    int i = findStrin.find(str, 0, length, search);
    System.out.println(i);
}

  public int find(String first[], int start, int end, String searchString){
    int mid = start + (end-start)/2;

    if(first[mid].compareTo(searchString)==0){
        return mid;
    }
    if(first[mid].compareTo(searchString)> 0){
        return find(first, start, mid-1, searchString);
    }else if(first[mid].compareTo(searchString)< 0){
        return find(first, mid+1, end, searchString);
    }
    return -1;
  }

答案 2 :(得分:0)

我相信您的问题是您忘记输出结果。尝试将binarySearch(numArray, searchItem);替换为System.out.println(binarySearch(numArray, searchItem));

答案 3 :(得分:0)

除了已经提到的结果缺失印刷品之外,我还可以发现四个问题。

1:您有一个名为String[]的{​​{1}},而您正在搜索numArrayString名称"The"可能有点误导

2:我假设您有某种指定的输入文件格式,其中文件中numArray的数量由String指定为文件中的第一个标记。这是正常的,因为填充integer的for循环中的条件有numArray,而下一个标记是使用in.hasNextInt()Scanner中取出的。您应该使用补充检查/删除方法,例如in.nextLine()in.hasNext()。查看in.next() API

3:Scanner方法使用binarySearch(String[], String)。这决定了此String.compareTo(String)对参数String的词典排序。尝试将大写字母与小写字母进行比较可能无法达到您的预期,因为String不会产生"the".compareTo("The")。您应该查看0 API选项,以便将所有输入强制转换为一个案例,可能是在读取文件时,或者使用与方法不同的比较风格。

4:我看到的最后一件事可能被认为是一个角落的情况,但是有一个足够大的String数组,以及一个可能位于右侧的搜索字符串,即。在数组的高索引侧,您可能会获得String。这是因为当结果“应该”大于ArrayIndexOutOfBoundsException时,(low + high)会导致负值。然后将结果除以2并仍然产生负值。这可以通过对结果进行位移而不是除以2 Integer.MAX_VALUE来解决。 Joshua Bloch关于分而治之算法的这个常见缺陷有一个很好的article

答案 4 :(得分:0)

@Mike Rylander发现,您忘记了输出结果。

您应该使用Arrays.binarySearch而不是自己的实现。

(作为一般规则,JRE库经过了良好的测试,良好的文档说明和快速的操作。我用Google搜索了“ java二进制搜索”,并且此问题的排名也不错。我尝试使用@Thusitha Indunil的代码,似乎没有用。我在Google上加倍努力,发现Arrays.binarySearch有效。)

相关问题