插入在C#中的字符串数组上排序

baf*_*mca 3 c# sorting algorithm insertion-sort

如果我有一个字符串数组,例如

string[] names = {"John Doe", "Doe John", "Another Name", "Name Another"};
Run Code Online (Sandbox Code Playgroud)

如何使用插入排序对此数组进行排序?

维基百科有一些例子: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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但它似乎不适用于我的字符串数组,除非我做错了.

我不会跑

InsertSort(names); // like so?
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 5

对我来说很好:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如所料,它打印:

Another Name
Doe John
John Doe
Name Another
Run Code Online (Sandbox Code Playgroud)