随机生成的搜索词错误

时间:2013-04-11 03:18:50

标签: java random

我正在研究一个问题,这个问题涉及我生成一定数量的数字(此处命名为“Jeff”)并搜索它们,然后记录时间,以便了解使用不同的任务执行任务所需的时间搜索算法。下面你会找到我到目前为止的内容,不包括binarySearch算法(有效)。我发现的问题是“搜索值”每次都会出现“未找到”。

我接受了Jeff接受Jeff数量(用户输入)的代码,然后是用户选择的搜索词。我对其进行了更改,以便随机生成的数字可以完全填充List,但这会阻止搜索工作。或者这就是看起来的样子。

一切都有帮助!

谢谢!

public static void main(String[] args) {

    long startTime = System.nanoTime();

    int Jeff = 20;

    List<Integer> intList = new ArrayList<Integer>(Jeff);
    int searchValue = 0, index;
    int temp;

    Random generator = new Random();

    System.out.println("Entering " + Jeff + " numbers...");
    //Adds unique values up to and through Jeff
    while (intList.size() < Jeff) {
            Integer next = generator.nextInt(Jeff) + 1;
            if (!intList.contains(next))
            {
                // Done for this iteration
                intList.add(next);
            }
    }
    System.out.println("List: " + intList);

    //Adding to ArrayList
    for (int i = 0; i < intList.size(); i++) {
        temp = generator.nextInt(Jeff) + 1;
        intList.set(i,temp);
    }
    System.out.print("Enter a number to search for: ");
    searchValue = generator.nextInt(Jeff) + 1;
    System.out.println(searchValue);

    index = binarySearch(intList, searchValue);

    if (index != -1) {
        System.out.println("Found at index: " + index);
    } 
    else {
        System.out.println("Not Found");
    }

    long endTime = System.nanoTime();
    long duration1 = endTime - startTime;
    System.out.println(duration1);
    }
  static int binarySearch(List<Integer> intList, int find) {
    long startTime2 = System.nanoTime();
    int start, end, midPt;
    start = 0;
    end = intList.size() - 1;
    while (start <= end) {
        midPt = (start + end) / 2;
        if (intList.get(midPt) == find) {
            long endTime2 = System.nanoTime();
            long duration2 = endTime2 - startTime2;
            System.out.println(duration2);
            return midPt;
        } else if (intList.get(midPt) < find) {
            start = midPt + 1;
        } else {
            end = midPt - 1;
        }
    }
    long endTime2 = System.nanoTime();
    long duration2 = endTime2 - startTime2;
    System.out.println(duration2);
    return -1;
    }
}

2 个答案:

答案 0 :(得分:1)

您在列表中填写随机数字。不幸的是,二进制搜索不能很好地工作。

例如,假设Jeff = 5。添加随机数后,您的列表可能如下所示:

[3, 1, 5, 2, 4]

现在,如果你搜索2,你首先要查看列表中点的元素是5.由于2小于5,然后你继续在列表的左半边查找它(即{ {1}})。显然,它不存在,因此您的搜索将失败。

您需要先对列表进行排序(这会使解决方案变得微不足道),或选择新的搜索策略。对于排序列表上的非平凡搜索,您可以搜索不限于[3, 1]的整数排序列表。


P.S。请不要将变量称为“Jeff”。它可能有点可爱,但它也不是一个好习惯,因为它妨碍了可读性。

答案 1 :(得分:0)

你确定searchValue在intList中吗?它看起来应该是

searchValue = intList.get(generator.nextInt(intList.size()));