我想问一下如何在我有50,000个结构的List中实现二进制搜索。
我按照 listSub.OrderBy(s => s.word);
word 对此列表进行排序public struct SubItem
{
public string word;
public int count;
public SubItem(string word, int count)
{
this.word = word;
this.count = count;
}
}
我不知道如何在列表< SubItem >中进行二元搜索。你能救我吗?
答案 0 :(得分:0)
二进制搜索的关键是中心项目左侧的所有项目都小于中心项目,右侧的项目都更大。另一个关键是列表的任何给定部分本身都表现为排序列表,因此该属性仍然适用。因此,在找到元素之前,请将列表分成两半。这通常使用递归来完成,使用空列表作为列表中不存在该元素的基本情况。
这是一些让你开始的伪代码:
find (list, start, end, target) {
if (start > end) // this is called a base case, look into recursion
return -1
center = (end - start) / 2
if list[center] == target // this is also a base case
return center;
else if list[center] > target
return find(list, start, center-1, target)
else
return find(list, center+1, end, target)
}
我们会像这样运行它:
list = [ 1 , 3, 7, 9, 12, 15, 17, 21, 28 ]
// need to find the target in the list
find(list, 0, list.length - 1, 3);
这首先看12,它比我们的目标大,所以然后它将列表分成两半,看看下半部分的中间是3并找到它,返回它的索引。它往往对更大和更大的列表更有利。
我说它使用递归,这意味着两件事:它会调用自己直到找到答案,并且当它找到答案时,它会停止调用自己。有两种主要的递归方法,你可能会在稍后发现,但最重要的部分是那两种:递归步骤(调用自身)和基本情况(当它停止调用自身时)。没有这两个部分,某些东西不是递归的。
答案 1 :(得分:0)
使用ArrayList。它有一个名为BinarySearch的方法。