我的列表中填充了文件名。我需要用搜索结果填充另一个列表。此搜索结果必须通过二进制搜索完成,具有下一个规范:关键字可以匹配文件名,或者它的子串(0,key.Length)。 例如keyword =“car” 搜索结果=“car.gif”,“carffur.pdf”等,但不是“mobilecar.jar”
我的二元搜索:
class Search
{
private const int KEY_NOT_FOUND = -1;
public static int BinarySearch<T>(List<T> A, T key, IComparer<T> comparer, int imin, int imax)
{
// test if array is empty
if (imax < imin)
// set is empty, so return value showing not found
return KEY_NOT_FOUND;
else
{
// calculate midpoint to cut set in half
int imid = imin + ((imax - imin) / 2);
int compareResult = comparer.Compare(A[imid], key);
// three-way comparison
if (compareResult > 0)
// key is in lower subset
return BinarySearch<T>(A, key, comparer,imin, imid - 1);
else if (compareResult < 0)
// key is in upper subset
return BinarySearch<T>(A, key, comparer, imid + 1, imax);
else
// key has been found
return imid;
}
}
}
我的比较者课程:
class SubStringComparison : IComparer<string>
{
public int Compare(string x, string y)
{
if (x.Length > y.Length && x.Substring(0, y.Length).Equals(y))
return 0;
return String.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
}
用法:
private void backgroundWorkerSearch_DoWork(object sender, DoWorkEventArgs e)
{
SearchForFiles();
}
private void SearchForFiles()
{
List<string> files = listBoxFiles.Items.OfType<string>().ToList();
searchResults = new List<string>();
listBoxFiles.Dispatcher.Invoke(new Action(delegate()
{
while (true)
{
int index = Search.BinarySearch<string>(files, textBoxFileToSearch.Text, new SubStringComparison(), 0, files.Count - 1);
if (index == -1)
break;
else
searchResults.Add(files[index]);
}
}));
}
答案 0 :(得分:0)
-1你的家庭作业哪部分有问题? 是二元搜索吗? 是文件名的选择吗? 是BackgroundWorker没有按预期工作吗?
我发现你在BackgroundWorker上遇到了一些问题,看来你是在BackgroundWorker线程中从UI中选择一个文件列表,然后创建一个将在主线程中运行的Action,这是一个很奇怪的方法。它
正确的方法是:
public void button1_Click(object sender)
{
List<string> files = listBoxFiles.Items.OfType<string>().ToList();
string key = textBoxFileToSearch.Text;
backgroundWorkerSearch.RunWorkerAsync(new Tupple<List<string>,string>(files, key));
}
void backgroundWorkerSearch_DoWork(object sender, DoWorkEventArgs e)
{
var state = e.Argument as Tupple<List<string>,string>;
List<string> files = state.Item1;
string key = state.Item2;
// You can now access the needed data.
List<string> searchResult = new List<string>();
// ...
e.Result = searchResult;
}
void backgroundWorkerSearch_RunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
List<string> searchResult = e.Result;
// Show result in the UI thread.
}