這是一個字符串9*8*0.01548
它在ArrayList<String>
。我需要基於Double
值進行二分搜索,例如0.01548
以找到搜索值的近似匹配。 ArrayList
包含大約100萬條記錄。 Split
在優化方面似乎不太好。 我嘗試了下面的代碼,但它不工作,因爲列表中間值是基於列表大小3
計算的。二進制搜索本身是好的我只是增加對問題的清晰,如果只是Double
值在arrayListvalues
然後二進制搜索做工精細字符串特定部分的二進制搜索
- 什麼是可能的替代方案?
- 如何使其工作?
下面是:
public static <T> int binarySearch(List<T> list, T key, Comparator<T> compare) {
int low, high, med, comp;
T temp;
high = list.size();
low = 0;
med = (high + low)/2;
while (high != low + 1) {
temp = list.get(med);
comp = compare.compare(temp, key);
if (comp == 0) {
return med;
} else if (comp < 0) {
low = med;
} else {
high = med;
}
med = (high + low)/2;
}
return med;
}
比較
public static class doubleComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
String[] d1 = s1.split("*"); //this
String[] d2 = s2.split("*"); //that
if (Double.parseDouble(d1[2]) < Double.parseDouble(d2[2])) {
return -1;
} else if (Double.parseDouble(d2 [2]) > Double.parseDouble(d2[2])) {
return 1;
} else {
return 0;
}
}
}
主要
public static void main(String[] args) {
ArrayList<String> strArray= new ArrayList<String>();
strArray.add("1*2*0.1");
strArray.add("3*4*0.5");
strArray.add("5*6*0.6");
strArray.add("7*8*0.7");
strArray.add("9*10*0.8");
strArray.add("11*12*0.9");
int key = binarySearch(strArray, "45*60*0.3", new doubleComparator());
System.out.println("Search for "45*60*0.3:"\tKey:" + key + "\tValue:" + strArray.get(key));
}
同意第二點'爲什麼不做預先計算'。謝謝! – Jamal