gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:49:29 25 4
gpt4 key购买 nike

我有一个通用的二分查找法,它对 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com