次のような文字列の配列がある場合
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?