在 java 中使用字符串二进制搜索有困难 - 在列表中找不到搜索键

Difficulty working with string binary search in java - search key not found in the list

我一直在尝试使用搜索键来获取此二进制搜索程序中的值。如果我将“CCC”作为元素之一并尝试使用搜索参数搜索它,它会成功获取,但是当我从元素列表中删除“CCC”并将搜索键更改为任何其他元素时,它不获取任何结果。

static String[] books = {
            "Rome", "King Arthur", "The Johnson's", "Romeo and Juliet", "Hoodlums", "Baptist",
            "Rogue", "Marc Anthony", "The survivor", "Arc of Grace", "France", "Holy",
            "Mayor", "Fatality", "Immortal", "Fidelity", "The Major", "In the Hood"
    };
    static int min = 0;
    static int max = books.length - 1;
    static int mid;
    static String key = "Rome";

    public static int stringBinarySearch() {
        while (min <= max) {
            mid = (min + max) / 2;
            if (books[mid].compareTo(key) < 0) {
                min = mid + 1;
            }
            else if (books[mid].compareTo(key) > 0) {
                max = mid - 1;
            } else {
                System.out.print("Book found and available at shelve ");
                return mid;
            }
        }
        System.out.println("Book not found");
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(stringBinarySearch());
    }

为了能够使用二进制搜索算法,您的数据集必须按搜索条件排序。

在此示例中,您按 books 的字符串进行比较,然后 books 必须首先按 a-z 顺序排序。

二进制搜索需要对数组进行排序。

由于数组未排序,您最好进行线性搜索,或者如果您将经常搜索,则对数组进行排序(使用 Arrays.sort(books)),然后您可以使用您的二进制文件搜索方法。