【问题标题】:JavaFX Binary Search - Issue with loopJavaFX 二进制搜索 - 循环问题
【发布时间】:2014-01-17 20:24:07
【问题描述】:

我在 JavaFX 中有 6 个文本字段 (number1-6) 和另一个名为“textfieldLF”的文本字段,它是用户正在搜索的数字。我正在尝试制作一个 JavaFX 程序,用于使用二进制搜索算法在 6 个不同的数字之间进行搜索,但由于某种原因它不起作用。

我使用了来自维基百科的算法。我检查了数组的索引以确保它们是正确的,因为第一个 if 条件和语句可以完美地单独工作。只有当它想确定它必须对中点做出什么改变时,我才认为它有问题。

代码:

@FXML
    private void handleButtonAction(ActionEvent event) {
        // First and last indexes declaration
        int imin = 1;
        int imax = 6;

        // Declare array for user inputs
        String[] NumbersArray = {number1.getText(), number2.getText(), number3.getText(), number4.getText(), number5.getText(), number6.getText()};

        // What to find? Get input from user
        String ToFind = textfieldLF.getText();

        // Match Index
        String MatchID;

        // Match Found? Boolean
        boolean MatchFound = false;

        // Find midpoint
        int imid = (int) ceil((double)((imin + imax) / 2));

        while (MatchFound = false)
        {
            // Try to find match in midpoint position
            if (NumbersArray[imid].equals(ToFind))
            {
                System.out.println("Match #" + (imid + 1));
                MatchFound = true;
            } else if(Integer.parseInt(NumbersArray[imid]) < Integer.parseInt(ToFind)) {
                imin = imid + 1;
                MatchFound = false;
            } else {
                imax = imid - 1;
                MatchFound = false;
            }
        }

    }

如果有任何帮助,我将不胜感激 谢谢

【问题讨论】:

  • 数字字段的值是否保证排序?如果您搜索的值不在数组中,我也看不到您退出循环的位置。是否有任何检查阻止用户在数字字段中输入未排序的值和在 textfieldLF 文本字段中输入不存在的值?
  • 在我的测试中,我尝试了从 1 到 6 的数字(分别在字段 1 到 6 中),反之亦然,但它没有打印出 Match # 或任何东西。我只是想让它以一种基本的方式工作,保证用户只会输入一个排序列表但没有检查。即使我不退出循环,它也不必工作吗?顺便谢谢你的回复!

标签: java search binary javafx


【解决方案1】:

它不起作用,因为你永远不会改变imid。它也不是二分搜索,因为不会每一步都将索引范围减少一半。

移动

int imid = (int) ceil((double)((imin + imax) / 2));

在循环内部(循环体的开头)。您仍然需要添加退出循环的方法。

你的起始索引也是错误的。数组的索引范围是 0-5 而不是 1-6。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-16
    • 2017-03-04
    • 2013-09-19
    • 2020-11-16
    • 2021-09-18
    • 2010-09-19
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多