我正在制作一个Android字典越南语 - 英语(超过20,000个条目)。 在我的应用程序中包含edittext和Listview。 要在我的列表视图中搜索项目,我使用二进制搜索。 但问题是搜索方法和越南语,它搜索不好 它可以找到一些词,有些则不能。
以下是我的搜索代码,用于在编辑文本更改时按字词前缀查找。
public void searchWords(String[] words, String prefix)
{
int first = 0, last = words.length - 1;
int mid = 0;
while (first <= last)
{
mid = (first + last) / 2;
int c = prefix.compareTo(words[mid]);
if (c == 0)
{
first = mid; // first indicates the beginning
break;
}
if (c > 0)
first = mid + 1;
else
last = mid - 1;
}
int i;
for (i = first; i < words.length; i++)
{
if (words[i].startsWith(prefix))
{
pos=i;
break;
}
}
lv.setSelection(pos);
// Toast.makeText(getApplicationContext(), ""+pos,Toast.LENGTH_SHORT).show();
}
和onTextchange代码我调用我的方法:
public void onTextChanged(CharSequence s, int start, int before, int count){
// TODO Auto-generated method stub
searchWords(w,s.toString());
}
这就是我将条目从数据库加载到数组的方式:
d=handle.retrieve();
if(d.moveToFirst())
{
do
{
w[ii++]=d.getString(1);
}while(d.moveToNext());
}
那么,我该怎么做才能使我的搜索工作正常?
答案 0 :(得分:1)
使用“compareTo()”的二进制搜索仅适用于SORTED单词(或排序的字符串,即按字母顺序排序 - 无论语言如何)。含义:数组以A,AA,AAA,......开头,以z,zz,zzz结尾... Btw,小写前大写。例如:
String[] seq = {"Ape", "Bird", "Donkey", "Eagle", "Fish", "Gnu", "Horse", "Koala"};
String[] ran = {"Gnu", "Koala", "Horse", "Fish", "Bird", "Donkey", "Eagle", "Ape"};
String[] queries = {"Eagle", "Bird", "Donkey", "Fish", "Ape", "Horse", "Eagle", "Gnu"};
// binarySearch with random[] will produce unpredictable results when prefix starts with
// a word that is either after "Bird" or "Ape" or "Gnu"
for (String s : queries) {
System.out.println("Random: BS for " + s + " = " + binarySearch(ran, s));
}
//
// binarySearch with sequence[] will produce correct results whatever prefix is.
for (String s : queries) {
System.out.println("Sequence: BS for " + s + " = " + binarySearch(seq, s));
}
//-------------------------------------------------------------------------
public static int binarySearch(String[] words, String value) {
return binarySearch(words, value, 0, words.length - 1);
}
//
public static int binarySearch(String[] words, String value, int min, int max) {
if (min > max) {
return -1;
}
int mid = (max + min) / 2;
if (words[mid].equals(value)) return mid;
if(words[mid].compareTo(value) > 0)
return binarySearch(words, value, min, mid - 1);
return binarySearch(words, value, mid + 1, max);
}