【发布时间】:2018-08-29 02:02:28
【问题描述】:
我遇到了一些麻烦。输入数组基于文件输入,数组的大小由文件的第一行指定。 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();
}
}
【问题讨论】:
-
调用
binarySearch时数组是否排序? -
是的,他们的排序。当数组中的元素被打印出来时,由于某种原因,它们都显示为 null。
-
这在什么方面不起作用?预期行为与实际行为是什么?你试过什么?
-
只是好奇,这是家庭作业吗?
Arrays.sort(numArray); Arrays.binarySearch(numArray, "The");可以替换大部分代码。
标签: java binary-search