package apc.dastruc.algorithms;
public class BinarySearch<K>{
public void bubbleSorting(K[] haystack){
int j = 0;
int i = 0;
int temp;
while(j < (haystack.length - j)){
while (i < (haystack.length - 1)){
if(haystack[i] > haystack[i + 1]){
temp = haystack[i];
haystack[i] = haystack[i - 1];
haystack[i - 1] = temp;
}
}
}
}
public int search(K[] haystack, K needle){
bubbleSorting(haystack);
int i = haystack.length / 2;
while(i > 0 && i > haystack.length){
if(needle.equals(haystack[i])){
return i;
}else if(needle < haystack[i]){
i--;
}else if(needle > haystack[i]){
i++;
}
}
return -1; //no match is found
}
}
问题是我们需要使它们成为泛型。所以我真的不能只是将它们的类型更改为 int。
如果 K 实现了 Comparable,那么你可以这样做:
if(needle.compareTo(haystack[i]) == 0){
return i;
} else if(needle.compareTo(haystack[i]) > 0){
i--;
} else {
i++;
}
您的代码还希望强制 K 实现 Comparable 才能做到这一点,即:
public class BinarySearch<K extends Comparable<K>>
我想你可能想看看可比较的界面。
在此行中,您尝试使用 >
运算符比较两个类型 K
的对象:
if(haystack[i] > haystack[i + 1]){
这是行不通的,因为您无法将任意对象与 >
进行比较。
解决这个问题的一种方法是对类型K
施加约束,指定它必须是实现Comparable<K>
的类型,然后使用 Comparable
的方法比较对象:
public class BinarySearch<K extends Comparable<K>> {
public void bubbleSorting(K[] haystack){
// ...
if (haystack[i].compareTo(haystack[i + 1]) > 0) {
// ...
}
}
}