我在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;
}
}
}
我将不胜感激任何帮助 感谢
答案 0 :(得分:0)
它不起作用,因为你永远不会改变imid
。它也没有二进制搜索,因为每一步都不会将索引范围缩小一半。
移动
int imid = (int) ceil((double)((imin + imax) / 2));
在循环内部(到循环体的开头)。你仍然需要添加退出循环的方法。
你的开始指数也是错误的。数组的索引范围是0-5而不是1-6。