【发布时间】:2011-04-24 11:16:10
【问题描述】:
如果我有一个字符串数组,比如
string[] names = {"John Doe", "Doe John", "Another Name", "Name Another"};
如何使用插入排序对这个数组进行排序?
维基百科有一些例子:https://en.wikibooks.org/wiki/Algorithm_implementation/Sorting/Insertion_sort#C.23
static void InsertSort(IComparable[] array)
{
int i, j;
for (i = 1; i < array.Length; i++)
{
IComparable value = array[i];
j = i - 1;
while ((j >= 0) && (array[j].CompareTo(value) > 0))
{
array[j + 1] = array[j];
j--;
}
array[j + 1] = value;
}
}
和
static void InsertSort<T>(IList<T> list) where T : IComparable<T>
{
int i, j;
for (i = 1; i < list.Count; i++)
{
T value = list[i];
j = i - 1;
while ((j >= 0) && (list[j].CompareTo(value) > 0))
{
list[j + 1] = list[j];
j--;
}
list[j + 1] = value;
}
}
但它似乎不适用于我的字符串数组,除非我做错了什么。
我不会跑
InsertSort(names); // like so?
【问题讨论】:
-
@Larsenal,不,我只是用一个简单的例子。
-
我敢打赌,您的
InsertSort(names);调用周围的客户端代码中存在拼写错误/错误。当您检查排序方法是否成功时,您可能只是引用了错误的数组。请发布您的客户端代码,而不是已经众所周知并经过测试的 InsertSort 方法。 -
我实际上是从文件中读取字符串,我将数组设置为 [16] 但行数实际上不是 16,所以我需要找到一种方法来拥有一个变量大小的数组。
-
如果你的需求是可变大小的数组,你也可以唱 List
标签: c# algorithm sorting insertion-sort