java - 使用字符串的通用二分搜索

标签 java arrays generics binary-search compareto

我有一个通用的二分搜索,它可以正确搜索 Array 中的Integers。但是,当应用于 StringsArray 时,它最多只能正确返回三个索引 ([1],[2],[3]),同时标记其他的视为不存在 ([-1])。预先感谢您的任何见解。

public class BinarySearch {

private BinarySearch() { }

private static <T extends Comparable<? super T>> int search(T[] list, int first, int last, T key){
    int foundPosition;
    int mid = first + (last - first) / 2;  
    if (first > last)
        foundPosition = -1;
    else if (key.equals(list[mid]))
        foundPosition = mid;
    else if (key.compareTo(list[mid]) < 0)
        foundPosition = search(list, first, mid - 1, key);
    else
        foundPosition = search(list, mid + 1, last, key);
    return foundPosition;
} 

public static void main(String args[]) {
    //Integer
    Integer [] searchInteger = {0,2,4,6,8,10,12,14,16};
    int integerLast = searchInteger.length-1;
    System.out.println("Integer test array contains...");
        for (Integer a1 : searchInteger) {
         System.out.print(a1 + " ");
        }
    System.out.println("\nChecking Integer array...");
    int result;
    for (int key = -4; key < 18; key++) {
        result = BinarySearch.search(searchInteger, 0, integerLast, key);
        if (result < 0)
            System.out.println(key + " is not in the array.");
        else
            System.out.println(key + " is at index " + result + ".");
        }
    //String
    String[] searchFruits = {"lemon", "apple", "banana", "peach", "pineapple", "grapes", "blueberry", "papaya"};      
    System.out.println("String test array contains...");
    for (String a1 : searchFruits) {
        System.out.print(a1 + " ");
    }
    System.out.println("\nChecking String array...");
    int results;
    int fruitLast = searchFruits.length-1;
    for (int key = 0; key < searchFruits.length; key++){
        results = BinarySearch.search(searchFruits, 0, fruitLast, searchFruits[key]);
        System.out.println("Key = " + searchFruits[key]);
        System.out.println("Index result = " + results);
        if (results < 0)
            System.out.println(searchFruits[key] + " is not in the array.");
        else
            System.out.println(searchFruits[key] + " is at index " + results + ".");        
    }
}
}

最佳答案

因为你的字符串数组

    String[] searchFruits = {"lemon", "apple", "banana", "peach", "pineapple", "grapes", "blueberry", "papaya"}; 

未排序,与您的整数数组相同

  Integer [] searchInteger = {0,2,4,6,8,10,12,14,16};

排序

顺便说一下,你可以使用 Arrays.binarySearch()也是。

关于java - 使用字符串的通用二分搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31391646/

相关文章:

c# - IList实现测试

java - 是否有用于编写 ply 文件的 Java 库?

java - 使用正则表达式获取 url 的最后一部分

javascript - Angular 在 orderBy 之后获取中间索引

javascript - Javascript 对象属性和数组之间的迭代有什么区别

java - 通配符(?) 有效,而类型 "T"在泛型中无效 - 为什么?

java - Android - 构造函数变量中的空指针异常

java - 如何为 Java HashMaps 模拟 Python dict "items()"方法?

javascript - 检查数组中的值

java - 递归方法中的泛型