首页 > 解决方案 > 排序后无法在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

我不明白我做错了什么。

标签: javaarrayssortingcharacterbinary-search

解决方案


推荐阅读