如果余有字符串,诸如阵列
字符串[]名称= {张三,李四约翰,别称,名称的另一个};
我如何排序了这阵,用插入排序?
维基百科有一些例子:https://secure.wikimedia.org/wikibooks/en/wiki/Algorithm_implementation/Sorting/Insertion_sort#C.23
静态无效InsertSort(IComparable的[]数组)
{
INT I,J;
对于(i = 1; I< array.Length;我++)
{
IComparable的值=数组[我]
J = - 1;
而((J> = 0)及及(阵列[J]。.CompareTo(值)大于0))
{
阵列[J + 1] =阵列[J]。
j--;
}
阵列[J + 1] =值;
}
}
和
静态无效InsertSort< T>(IList的< T>清单)其中T:IComparable的< T>
{
INT I,J;
对于(i = 1; I< list.Count;我++)
{
t值=列表[我]
J = - 1;
而((J> = 0)及及(名单[J]。.CompareTo(值)大于0))
{
清单[J + 1] =列表[J]。
j--;
}
清单[J + 1] =值;
}
}
但它似乎并没有工作,我的字符串数组上,除非我做错了什么。
我会无法运行。
InsertSort(名称); // 像这样?
解决方案我
正常工作:
类节目
{
静态无效的主要()
{
字符串[]名称= {张三,李四约翰,别称,名称的另一个};
InsertSort(名称);
的foreach(在名称VAR项)
{
Console.WriteLine(项目);
}
}
静态无效InsertSort(IComparable的[]数组)
{
INT I,J;
对于(i = 1; I< array.Length;我++)
{
IComparable的值=数组[我]
J = - 1;
而((J> = 0)及及(阵列[J]。.CompareTo(值)大于0))
{
阵列[J + 1] =阵列[J]。
j--;
}
阵列[J + 1] =值;
}
}
}
正如预期的那样将打印:
另一个名称
约翰·多伊
李四
名称的另一个
If I have an array of strings, such as
string[] names = {"John Doe", "Doe John", "Another Name", "Name Another"};
How do I sort this array, using insertion sort?
Wikipedia has some examples: https://secure.wikimedia.org/wikibooks/en/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;
}
}
and
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;
}
}
but it doesn't seem to work on my array of strings, unless I'm doing something wrong.
Would I not run
InsertSort(names); // like so?
解决方案
Works fine for me:
class Program
{
static void Main()
{
string[] names = { "John Doe", "Doe John", "Another Name", "Name Another" };
InsertSort(names);
foreach (var item in names)
{
Console.WriteLine(item);
}
}
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;
}
}
}
As expected it prints:
Another Name
Doe John
John Doe
Name Another