【问题标题】:Generic Binary Search Using String使用字符串的通用二进制搜索
【发布时间】:2015-07-13 19:18:13
【问题描述】:

我有一个通用的二进制搜索,它在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 + ".");        
    }
}
}

【问题讨论】:

    标签: java arrays generics binary-search compareto


    【解决方案1】:

    因为你的字符串数组

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

    未排序,作为整数数组

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

    排序

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2021-04-15
      • 1970-01-01
      • 2015-06-15
      • 2020-09-27
      • 2011-04-21
      相关资源
      最近更新 更多