加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:38:39 所属栏目:百科 来源:网络整理
导读:如果我有一个字符串数组,例如 string[] names = {"John Doe","Doe John","Another Name","Name Another"}; 如何使用插入排序对此数组进行排序? 维基百科有一些例子:https://en.wikibooks.org/wiki/Algorithm_implementation/Sorting/Insertion_sort#C.23 s
如果我有一个字符串数组,例如

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?

解决方法

对我来说很好:

class Program
{
    static void Main()
    {
        string[] names = { "John Doe","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;
        }
    }
}

正如所料,它打印:

Another Name
Doe John
John Doe
Name Another

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读