我遇到了无法应用索引的错误,但我不确定如何为BinarySearch建立一个'边界'(代数)来查找字符串。很明显
if (item > N[mid])
无法运行,因为item是一个字符串。如何在此找到项目?:
public static int BinarySearch(string[] name, string item)
{
int min = 0;
int N = name.Length;
int max = N - 1;
do
{
int mid = (min + max) / 2;
if (item > N[mid])
min = mid + 1;
else
max = mid - 1;
if (name[mid] == item)
return mid;
//if (min > max)
// break;
} while (min <= max);
return -1;
}
并试图用这样的东西安抚它
public static int BinarySearch(string[] name, string searchKeyword)
{
int min = 0; //=0
int N = name.Length; //.Length
int max = N - 1;
int S = searchKeyword.Length;
do
{
int mid = (min + max) / 2;
if (S > N[mid])
min = mid + 1;
else
max = mid - 1;
if (name[mid] == S)
return mid;
//if (min > max)
// break;
} while (min <= max);
return -1;
}
答案 0 :(得分:0)
你不能在字符串中使用>
运算符,因为C#在说一个字符串比另一个字符串更大时不知道你是什么意思。你按长度,字母顺序进行比较......?
如果您想按字母顺序对它们进行排序,请改用String.Compare方法:
public static int BinarySearch(string[] name, string item)
{
int min = 0;
int N = name.Length;
int max = N - 1;
do
{
int mid = (min + max) / 2;
if (String.Compare(item, name[mid]) > 0)
min = mid + 1;
else
max = mid - 1;
if (String.Compare(item, name[mid]) == 0)
return mid; //if (min > max)
// break;
} while (min <= max);
return -1;
}