【问题标题】:How to make flexible sort如何进行灵活排序
【发布时间】:2023-03-10 01:25:02
【问题描述】:

我想使用IComparable & IComparer 进行灵活排序,并将排序方法作为参数Object[] & IComparer 输入。而且我只能放链接类型,原始类型数组怎么放?

private void QuickSort(Object[] comparables, int low, int high)
{
    if (comparables.Length == 0)
    {
        return;
    }

    if (low >= high)
    {
        return;
    }

    int middle = low + (high - low) / 2;

    Object backbone = comparables[middle];

    int i = low;
    int j = high;
    while (i <= j)
    {
        //while (comparables[i].CompareTo(backbone) < 0)
        while (_comparator.Compare(comparables[i], backbone) < 0)
        {
            i++;
        }

        //while (comparables[j].CompareTo(backbone) > 0)
        while (_comparator.Compare(comparables[j], backbone) > 0)
        {
            j--;
        }

        if (i <= j)
        {
            Object temp = comparables[i];
            comparables[i] = comparables[j];
            comparables[j] = temp;
            i++;
            j--;
        }
    }

    if (low < j)
    {
        QuickSort(comparables, low, j);
    }

    if (high > i)
    {
        QuickSort(comparables, i, high);
    }
}

public void QuickSort(Object[] comparables, SortOrders order)
{
    _comparator = SortFactory.Instance.GetComparer(order);
    QuickSort(comparables, 0, comparables.Length - 1);
}

【问题讨论】:

    标签: c# algorithm sorting computer-science quicksort


    【解决方案1】:

    使用C# generics 参数化和限制函数参数类型。

    实现示例:

    public static void QuickSort<T>(T[] a, int from, int to, IComparer<T> comparer)
    {
        ...
        if (comparer.Compare(a[i], pivot) < 0)
    
    
    public static void QuickSort<T>(T[] a, int from, int to) where T : IComparable<T>
    {
        ...
        if (a[i].CompareTo(pivot) < 0)
    

    更多信息请查看:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-27
      • 2017-07-06
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多