我有一个学生名单,我想按姓氏对他们进行排序。学生列表看起来有点像这样:
Amanda
Dorris
Tucker
Yasmin
Zara
我想用二分法搜索这些学生,输出想要的结果。
这是我到目前为止所拥有的:
public void binarySearch(String keyword) {
int output;
if (fileSorted == false) {
System.out.println("The file " + fileName + " is not sorted. Please wait while it gets sorted...");
bubbleSort();
System.out.println("Thank you for your patience.");
System.out.println();
System.out.print("Search for: ");
keyword = elmo.nextLine();
output = doBinarySearch(keyword);
} else {
output = doBinarySearch(keyword);
}
System.out.println(output);
}
public int doBinarySearch(String keyword) {
int start = 0;
int end = numStudents - 1;
int mid;
int result;
while (start < end) {
mid = start + (end - start) / 2;
result = students[mid].returnLastName().compareToIgnoreCase(keyword);
if (result == 0) {
return mid;
} else if ((end - start) <= 1 ) {
return -1;
} else if (result > 0) {
start = mid;
} else if (result < 0) {
end = mid;
}
}
return -1;
}