c# 数组与列表通用排序算法

只需要给出权重的算法即可调用算法完成排序, 支持List Array

上代码:

public static class SortHelper
{
    /// 
    /// 要排序的元素
    /// 
    private class SortItem
    {
        public object data;

        public int weight;
    }

    private class SortItemComparer : IComparer
    {
        public int Compare(SortItem x, SortItem y)
        {
            if (x.weight > y.weight)
                return 1;
            if (x.weight < y.weight)
                return -1;
            return 0;
        }
    }

    private static readonly IComparer sortItemComparer = new SortItemComparer();

    /// 
    /// 排序列表,缓存数据
    /// 
    private static List sortItemList = new List();

    public static void Sort(this List lst, Func GetWeight)
    {
        if (lst == null || lst.Count <= 0)
            return;

        int cnt = lst.Count;
        for (int i = 0; i < cnt; i++)
        {
            if (sortItemList.Count <= i)
                sortItemList.Add(new SortItem());
            sortItemList[i].weight = GetWeight(lst[i]);
            sortItemList[i].data = lst[i];
        }

        sortItemList.Sort(0, cnt, sortItemComparer);
        for (int i = 0; i < cnt; i++)
        {
            //交换
            lst[i] = (T)sortItemList[i].data;
        }
    }

    public static void Sort(this T[] array, Func GetWeight)
    {
        if (array == null || array.Length <= 1)
            return;

        int cnt = array.Length;
        for (int i = 0; i < cnt; i++)
        {
            if (sortItemList.Count <= i)
                sortItemList.Add(new SortItem());
            sortItemList[i].weight = GetWeight(array[i]);
            sortItemList[i].data = array[i];
        }

        sortItemList.Sort(0, cnt, sortItemComparer);
        for (int i = 0; i < cnt; i++)
        {
            array[i] = (T)sortItemList[i].data;
        }
    }
}

你可能感兴趣的:(c#)