【发布时间】:2016-04-16 11:40:33
【问题描述】:
基本上,我需要帮助调整我的二分搜索算法以使用我的字符串列表,如下所示。 注意,我必须使用书面的二分搜索算法,不要使用 .BinarySearch 之类的内置 c# 函数。
我现在将向您展示列表的格式以及列表本身:
// This class formats the list, might be useful to know
public class Demo
{
public string Col;
public string S1;
public string S2;
public string S3;
public override string ToString()
{
return string.Format("Col: {0}, S1: {1}, S2: {2}, S3: {3}", Col, S1, S2, S3);
}
}
// The list itself
var list = new List<Demo>
{
new Demo {Col = "Blue", S1 ="88", S2 ="Yes"},
new Demo {Col = "Green", S1 ="43", S2 ="Yes"},
new Demo {Col = "Red", S1 ="216", S2 ="No"},
new Demo {Col = "Yellow", S1 ="100", S2 ="No"}
};
列表已经按照“Col”字符串值的字母顺序排序,因此蓝色排在第一位,黄色排在最后。 “Col”是列表中需要搜索的部分。下面我插入了我当前可以搜索 int 数组的二进制搜索。
public static int BinarySearch_R(int key, int[] array, int low, int high)
{
if (low > high) return -1;
int mid = (low + high) / 2;
if (key == array[mid])
{
return mid;
}
if (key < array[mid]) {
return BinarySearch_R(key, array, low, mid - 1);
} else {
return BinarySearch_R(key, array, mid + 1, high);
}
}
我需要帮助调整我的 BinarySearch 算法以适用于上面的列表。如果你们有任何问题,或者需要查看我的更多代码,请尽管提问。
【问题讨论】:
-
@jdweng 我问了一个稍微不同的问题。不想争论就说:)
-
@Fabien 我问了一个稍微不同的问题。不想争论就说:)
-
您拥有的不是字符串列表,而是自定义类 (
Demo) 列表。您最好更新帖子标题(例如“*二分搜索算法通过列表元素的属性”),因为它具有误导性。
标签: c# algorithm list binary-search