java - 排序后无法在java中的字符数组上进行二进制搜索
问题描述
所以我的任务是首先对字符数组进行排序。然后对其应用二进制搜索以找到特定的字母表。这是我的代码:
Scanner keyboard = new Scanner(System.in);
char[] charArray = new char[5];
System.out.println("Please enter 10 alphabetic characters: ");
for (int i = 0; i < charArray.length; i++)
charArray[i] = keyboard.next().charAt(0);
for (int i = 0; i < charArray.length; i++) {
for (int j = i + 1; j < charArray.length; j++) {
if (Character.toLowerCase(charArray[j]) < Character.toLowerCase(charArray[i])) {
swapChars(i, j, charArray);
}
}
}
System.out.println("Sorted alphabets: " + String.valueOf(charArray));
System.out.println("Enter alphabet you want to search: ");
char key = keyboard.next().charAt(0);
int result = binarySearch(charArray, 10, key);
if (result == -1) {
System.out.println("The alphabet " + key + "was not found.");
} else {
System.out.println("The alphabet " + charArray[result] + " is found at " + result + " index.");
}
}
private static void swapChars(int i, int j, char[] charArray) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
static int binarySearch(char charArray[], int used, char letterToFind) {
int first = 0;
int last = used - 1;
int mid;
int position = -1;
boolean found = false;
while (!found && first <= last) {
mid = (first + last) / 2;
if (charArray[mid] == letterToFind) {
found = true;
position = mid;
} else if (charArray[mid] > letterToFind)
last = mid - 1;
else
first = mid + 1;
}
return position;
}
我的程序运行得很好,但问题是当我输入一个数组中不存在的用于搜索的字母时,它给了我错误:java.lang.ArrayIndexOutOfBoundsException
我不明白我做错了什么。
解决方案
推荐阅读
- batch-file - 我需要每隔几秒钟运行一个批处理文件。我该怎么做?
- javascript - onClick 删除边框,然后在下一次单击时再次添加它们 CSS,Preact
- python - 如何安装模块 cyruslib
- javascript - 如何以数组形式访问 JavaScript 对象
- c# - 显示模式对话框时如何解决滚动问题?
- cakephp - 如何在多个函数中使用 CookieCollection
- oracle - PL/SQL 中多个特定异常的共享代码
- excel - 如何使用 VB.Net 更改 Excel 图表数据
- c++ - 如何使用 int16_t 值的低字节和高字节?
- c++ - 如何检测一个类是否具有 C++ 中的隐式构造函数和原始成员?